I am creating an API using Node.Js and MySQL and I am trying to structure the data when it is returned.
I am POSTing the following to create a new record
{
"SiteName" : "My Site",
"PitchTypes" : {
"TentPitches": true
}
}
This creates a new entry into the database correctly and then returns the data. However, it is returning the following. How can I format the data into the same format it was submitted in.
{
"id": 1,
"SiteName": "My Site",
"TentPitches": true
}
I have the following in my model and controller
campsite.models.js
exports.create = (req, res) => {
// Validate request
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!"
});
}
// Create a Record
const campsite = new Campsite({
SiteName: req.body.SiteName,
TentPitches: req.body.PitchTypes.TentPitches
});
// Save Campsite in the database
Campsite.create(campsite, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while creating the Campsite."
});
else res.send(data);
});
};
campsite.controllers.js
const Campsite = function(campsite) {
this.SiteName = campsite.SiteName;
this.TentPitches = campsite.TentPitches;
};
Campsite.create = (newCampsite, result) => {
sql.query("INSERT INTO campsites SET ?", newCampsite, (err, res) => {
if (err) {
console.log("error: ", err);
result(err, null);
return;
}
console.log("created campsite: ", { id: res.insertId, ...newCampsite });
result(null, { id: res.insertId, ...newCampsite });
});
};
my MySQL database has the following table
CREATE TABLE `campsites` (
`Id` int(5) NOT NULL AUTO_INCREMENT,
`SiteName` varchar(256) NOT NULL,
`TentPitches` tinyint(1),
`TentPitches_Electric` tinyint(1),
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
res.send(data)in the model, it's returning the data it's created so I can manipulate it here to appear in a different format.