1 Sep 2013

Insert a Document into MongoDB using node.js and mongojs

Insert a document into a MongoDB database using the mongojs module under 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 data = {
    make: "Nokia",
    model: "Lumia"

  db.products.insert(data, function(err, result) {
    if(err) { throw err; }
    res.write("<p>Product inserted:</p>");
    res.end("<p>" + result[0].make + " " + result[0].model + "</p>");


Start the node instance:

$ node server.js

Test in your browser:

Product inserted:
Nokia Lumia