Getting Started With Node – Course

MongoDB with Node

MongoDB is one of the most popular general purpose NoSQL database engines. You can use MongoDB to develop a wide range of application.

To be able to experiment with MongoDB, you need to install the MongoDB database in your system. Click here to visit the official site and download the latest version of MongoDB.

Assuming you have MongoDB installed, let’s install the MongoDB driver for Node.

npm install --save mongodb

We need to require the module and then connect to MongoDB instance.

Here is the code.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017/test";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
        if(err) {
           console.log(err);
           process.exit(0);
        }
        console.log('database connected!');
        db.close();
});

MongoDB runs on port 27017. We can connect to any database we like to work with. In the code shown above, we are connecting to test database.

We are using connect() method to establish a connection with the database.

Save the code above in a file called “app.js” and run the file:

node app.js

You should see output similar to this:

mongodb connection

In order to store data in MongoDB database you need to create a collection. Think of collection as a table in SQL database.

You can either create a collection in MongoDB shell or you can do it in code. Here is how you can do it in code.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017/";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
        if(err) {
           console.log(err);
           process.exit(0);
        }
        console.log('database connected!');
        var dbo = db.db('test');
        dbo.createCollection('customers', (err, result) => {
            if(err) {
               console.log(err);
               process.exit(0);
            }
            console.log('collection created!');
            db.close();
        });
});

Let’s try to insert some data in MongoDB collection.

MongoDB stores data in a JSON format. JSON is a key-value based data format widely used across various layers of softwares.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017/";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
        if(err) {
           console.log(err);
           process.exit(0);
        }
        let data = {
           "id": 100,
           "name": "Shahid"
        };
        var dbo = db.db('test');
        console.log('database connected!');
        dbo.collection('user').insert(data, (err, result) => {
           if(err) {
              console.log(err);
              process.exit(0);
           }
           console.log("records added.");
           console.log(result);
           db.close();
        });
});

You can also search for the data inside collection using findOne() function.

const mongo = require('mongodb');
const url = "mongodb://localhost:27017/";

mongo.connect(url, {useNewUrlParser: true}, (err, db) => {
        if(err) {
           console.log(err);
           process.exit(0);
        }
        let data = {
           "id": 100,
           "name": "Shahid"
        };
        var dbo = db.db('test');
        console.log('database connected!');
        dbo.collection('user').findOne({}, (err, result) => {
           if(err) {
              console.log(err);
              process.exit(0);
           }
           console.log("Here is the record");
           console.log(result);
           db.close();
        });
});

After running the code above, you should see a record similar to this.

MongoDB Find

You can also perform tons of other operations such as query(), sort(), delete() etc.

Learn more about MongoDB here.

2 Comments

Leave a Reply to Shahid Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.