How to insert documents to MongoDB with CoffeeScript

Install CoffeeScript

sudo npm install -g coffee-script

Install MongoDB driver for Node.JS

sudo npm install -g mongodb

Install shortid if you want Primary key instead of ObjectID.

sudo npm install -g shortid

Link installed modules to local dir

npm link mongodb
npm link shortid

Let’s get around to setting up a connection with the Mongo DB database. To work with the database, you first need to create a connection.

mcl = require('mongodb').MongoClient
sid = require('shortid')

mcl.connect("mongodb://localhost:27017/sandbox", (err, db) ->
    if !err
        console.log("We are connected");
        db.close()
);

# run: coffee fill.coffee

Collections are the equivalent of tables in traditional databases and contain all your documents. A database can have many collections.

In following snippet we are inserting 10 countries in City collection.

mcl = require('mongodb').MongoClient
sid = require('shortid')

mcl.connect("mongodb://localhost:27017/sandbox", (err, db) ->
    if !err
        console.log("We are connected");

        City = db.collection('City')

        City.remove({})

        for i in [0..10000]
            City.insert({_id: sid.generate(), title: "City #{i}", isCapital: false})

        db.close()
);

There are a couple of things to keep in mind when using the mongodb native driver:

  1. The query function names and their parameters are similar to that of native mongodb commands.

  2. All these query functions take the callback as the last argument. The callback function gives the first argument as error and the second argument as result. Result is actually result/output provided by the mongodb on running these commands. It is similar to what you see if you had run these queries in the mongodb shell.

Updating the documents in MongoDB.

City.update({title: 'City 7'}, {$set: {isCapital: true}}, (err, numUpdated) ->
    if err
        console.log(err);
    else if numUpdated
        console.log("Updated successfully #{numUpdated} document(s).");
    else
        console.log('No document found!');

    db.close();
)

Querying the documents in MongoDB.

cursor = City.find({isCapital: true});
cursor.sort({title: -1});

cursor.each((err, doc) ->
    if err
        console.log(err);
    else
        console.log('Fetched:', doc);
);
comments powered by Disqus