Connecting and Accessing MongoDB in Node.js

Learn how to connect and interact with MongoDB using Node.js. This tutorial covers the installation and setup of the MongoDB driver, starting the MongoDB server, and provides an example of connecting to a local MongoDB database for performing various database operations.



Access MongoDB in Node.js

Learn how to access the MongoDB database using Node.js.

Installation and Setup

First, install the MongoDB driver using NPM:

Syntax

npm install mongodb --save

This adds the MongoDB driver to your node_modules folder. Start the MongoDB server with:

Syntax

mongod --dbpath C:\MyNodeJSConsoleApp\MyMongoDB

Connecting MongoDB

Example of connecting to a local MongoDB database:

Syntax

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

MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
    if (err) throw err;
    // Write database Insert/Update/Query code here..
});

Insert Documents

Example of inserting documents into MongoDB:

Syntax

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

MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
    if (err) throw err;

    db.collection('Persons', function (err, collection) {
        if (err) throw err;

        collection.insert({ id: 1, firstName: 'Steve', lastName: 'Jobs' });
        collection.insert({ id: 2, firstName: 'Bill', lastName: 'Gates' });
        collection.insert({ id: 3, firstName: 'James', lastName: 'Bond' });

        db.collection('Persons').count(function (err, count) {
            if (err) throw err;
            console.log('Total Rows: ' + count);
        });
    });
});

Update/Delete Documents

Example of updating and deleting documents:

Syntax

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

MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
    if (err) throw err;

    db.collection('Persons', function (err, collection) {
        if (err) throw err;

        collection.update({ id: 1 }, { $set: { firstName: 'James', lastName: 'Gosling' } }, { w: 1 },
            function (err, result) {
                if (err) throw err;
                console.log('Document Updated Successfully');
            });

        collection.remove({ id: 2 }, { w: 1 }, function (err, result) {
            if (err) throw err;
            console.log('Document Removed Successfully');
        });
    });
});

Query Database

Example of querying the MongoDB database:

Syntax

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

MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
    if (err) throw err;

    db.collection('Persons', function (err, collection) {
        if (err) throw err;

        collection.find().toArray(function (err, items) {
            if (err) throw err;
            console.log(items);
        });
    });
});

Mongoose

Mongoose is a popular ODM (Object Data Modeling) library for MongoDB and Node.js, providing a straightforward schema-based solution to model your application data.