1 Sep 2013

Update a MongoDB document using node.js and mongojs

Update a document in a MongoDB database using the mongojs module and node.js.

Have you completed the getting started with Mongo steps?

If you haven't already, install the mongojs module using npm:

$ sudo npm install mongojs

Edit server.js:

var http = require("http");
var mongo = require("mongojs");

var db = mongo.connect("shop", ["products"]);

http.createServer(function(req, res) {

  var update = {
    // SET model = 'iPad 3' 
    $set: { model: "iPad 3"}
  };

  var query = {
    // WHERE model = 'iPad' 
    model: "iPad"
  };

  db.products.update(query, update, function(err, result) {
    if(err) { throw err; }
    res.end("<p>Product updated</p>");
  });

}).listen(8080);

Start the node instance:

$ node server.js

Test in your browser:

http://localhost:8080
Product updated