Home > Dev Tools | General > MongoDB and Node.js

MongoDB and Node.js

MongoDB and Node.js together is better than peanut butter and chocolate. In order to use MongoDB with Node.js you need to install the mongodb module. To do this use the Node.js package manager or npm for short. I had to install that separately, but its quite simple: http://npmjs.org/ to do. Once you have the package manager installed type:

$ npm install mongodb

You should see something similar to:

> mongodb@0.9.6-7 install /home/swright/code/mongo_test/node_modules/mongodb
> bash ./install.sh
 
================================================================================
=                                                                              =
=  To install with C++ bson parser do    =
=  the parser only works for node 0.4.X or lower                               =
=                                                                              =
================================================================================
./install.sh: line 9: [: too many arguments
Not building native library for cygwin
Using GNU make
mongodb@0.9.6-7 ./node_modules/mongodb

Dont worry about the parser line it does not apply to what we are doing. The next step is to write a test program.

GLOBAL.DEBUG = false;
 
var mongodb = require('mongodb')
mongoserver = new mongodb.Server(
    'localhost',
    mongodb.Connection.DEFAULT_PORT,
    {
        native_parser:false,
        strict:true // Prevents from auto-creating objects if they dont exist
    }
    ),
db_connector = new mongodb.Db(
    'node-test',
    mongoserver
    );
 
db_connector.on('close', function(){
    console.log('DB Connection Closed.');
});
 
db_connector.open(function(err, db){
    if(err){
        console.log("Connection error:" + err);
        return false;
    }
    console.log('DB Connection Open.')
 
    /*
    // Getting contents as an array.
    db.collection('urls', function(err, collection){
        collection.find().toArray(function(err, docs){
            console.log(docs);
        });
    });
    */
    // Getting contents as a cursor
    db.collection('urls', function(err, collection){
        collection.find({}, function(err, cursor){
 
            cursor.count(function(err, count){
                console.log('Total matches: ' + count);
            });
 
            cursor.each(function(err, doc){
                if(err) {
                    console.log(err)
                }
                /*
                 *  You must check if the doc is defined. For some reason
                 *  the cursor iterates record count + 1 and you will
                 *  get a null record as the last one.
                 */
                if(doc) {
                    console.log(doc);
                }
            })
        });
    });
 
    /*
    // Inserting data
    db.createCollection('urls', function(err, collection){
        if(err){
            console.log("Could not create collection:" + err);
            return false;
        }
        console.log('Collection created');
 
        collection.insert({
            'url':'google.com'
        });
    });
     */
});

A couple of gotchas.

  1. Make sure to set the server option “native_parser” to false
  2. The cursor seems to return one more record than what is actually there, so test to make sure that you have a record before working with it.
I like to set the “strict” server option to true to prevent auto-creation of objects in the DB.

,

Comments are closed.

TOP