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 ...

Get JavaScript JSON Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.