Using REST to update a document in MongoDB
Updating is identical to insertion, except that it needs a document ID and the client signals an update request with a HTTP POST
request, rather than a PUT
request.
How to do it...
The client code is exactly the same as the previous recipe; only the server code changes because it needs to extract the ID from the URL and perform an update instead of an insert:
exports.updateDocuments = function(req, res) { var id = new objectId(req.params.id); var document = req.body; db.collection('documents', function(err, collection) { collection.update({'_id':id}, document, {safe:true}, function(err, result) { if (err) { console.log('Error updating documents: ' + err); res.send({'error':'An error has occurred'}); } else { console.log('' + result + ' document(s) updated'); res.send(documents); } }); }); };
Let's look at that in more detail.
How it works…
Returning to the client implementation...