I want to add a new element in my Database and i'd like to get the created Id. (using node.js)
At the moment, I use an Ajax Post to add the element in the DB but I can't figure how to get the returning ID.
Should I use a GET or is there a way to get the id with my POST ? What is the best practive ?
Here's some code samples:
Client Script:
ajaxPost('/newElement', element, function(idDB) {
alert(idDB); //it says undefined
});
function ajaxPost(path, data, callback) {
$.ajax('http://'+ url + path, {
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
success: function() { if ( callback ) callback(); },
error : function(XMLHttpRequest, textStatus, errorThrown) { if ( callback ) callback(); }
});
}
Server
app.post('/newElement', function(req, res) {
queryDB.InsertElement(client, req.body, function(err, idDB) {
if (err) {
console.error(err);
res.end();
} else {
console.log(idDB); //I have the returned id here...
res.send(idDB);
}
});
});
Many Thanks.
The best practice is to use POST, ideally you should never change the state of the data with VERBS other than PUT and POST. PUT is preferred for database updates, and POST to create new entities, so, POST is better on this case
I suggest returning (in the POST) the element encoded as JSON (like a GET)