NodeJS MongoDB Tutorial

As a cornerstone of the popular MEAN stack, MongoDB has become very popular option for back end databases. It's written in JavaScript, making it extremely easy to for even front end developers to pick up. MongoDB's document-oriented structure provides high performance and scalability for web apps. The following tutorial is for getting started with MongoDB and your Node based project.

This tutorial assumes you have a Node.js project already set up. For more information on creating Node.js projects, see Getting Started With Node.js and Express. It's also assumed that a Mongo instance has already been installed and configured. For more information on installing MongoDB, see the official MongoDB site.


    Install MongoDB driver

    Node's npm makes it extremely easy to interact with an existing mongoDB installation. Simply run:

    npm install mongodb --save

    This will install the mongoDB module and save it to your project's dependencies.

    Connecting to the database

    Now that you have the mongoDB client, it's time to establish a connection to your existing database. The following is an example of how to connect:

    //include Mongo Client
    var MongoClient = require('mongodb').MongoClient
    //define database location
    var url = 'mongodb://localhost/yourwebapp';

    Now that you have a connection configured, it's time to actually connect to to the database via the defined client:

    MongoClient.connect(url, function(err, db) {
    var collection = db.collection('posts');
    collection.find({}).toArray(function(err, docs) {

    This example does a few things. It first establishes a connection to the defined database URL. The callback function returns any error message and the db instance (if successful). With this returned instance, you can run read/write operations on the database. In this particular instance, we are using express to render an EJS template (blog.ejs). We are passing the returned documents from the collection to a template variable (posts).

    While this example uses Express and EJS to render a response from the web server, you can perform virtually any operation within the connection block.

    Your thoughts?