MongoDB and Node.js example

The following code provides a brief reference example of reading data from a MongoDB database using Node.js. 


The following is already in place:

  • I've created a database in MongoDB called beetleJuice
  • Within the beetleJuice database, I've created a collection called bugs
  • The mongo dependency has been saved to the project directory
  • I have an instance of MongoDB running on port 27017
// Bring in the MongoDB dependency

var MongoClient = require('mongodb').MongoClient, assert = require('assert');

// Connect to the database

MongoClient.connect('mongodb://localhost:27017/beetleJuice', function (err, db) {
    assert.equal(null, err);
    // assign the bugs collection to var col
    var col = db.collection('bugs');
    // use the findOne method to search for a document where assignee is set to Daniel Hoadley
    col.findOne({"assignee" : "Daniel Hoadley"}, function (err, doc) {
        assert.equal(null, err);
    // Print the resulting document to the console
        console.log("Here is my doc: %j", doc);
    // Close the connection to the database