Updating a document in MongoDB with Node.js

Updating a document in a collection is easy; simply use the collection's update method and pass the data you want to update.

How to do it...

Here's a simple example:

var mongo = require('mongodb').MongoClient; var url = 'mongodb://localhost:27017/test'; var update = function(collection, callback) { collection.update({ call:'kf6gpe-7' }, { $set: { lat: 39.0, lng: -121.0, another: true } }, function(error, result) { console.log('Updated with error ' + error); console.log(result); callback(result); }); }; mongo.connect(url, function(error, db) { console.log("mongo.connect returned " + error); // Get the documents collection var collection = db.collection('documents'); update(collection, function(result) { ...

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.