Open In App

Native MongoDB driver for Node.js

Improve
Improve
Like Article
Like
Save
Share
Report

The native MongoDB driver for Node.JS is a dependency that allows our JavaScript application to interact with the NoSQL database, either locally or on the cloud through MongoDB Atlas. We are allowed to use promises as well as callbacks that gives us greater flexibility in using ES6 features. 

In order to start working with the MongoDB driver, we shall first create a new folder and initialize our project: 

npm init -y

Here, -y is a flag which will initialize our project with default values.
 

We will install the MongoDB driver and save it as a dependency with the following command: 

npm install mongodb --save

In our JavaScript entry point file, for the sake of convenience, we shall name app.js and we will write the following code to connect to the server: 

JavaScript




// Importing MongoClient from mongodb driver
const { MongoClient } = require('mongodb');
 
// Connecting to a local port
 
const client = new MongoClient(uri, {
    useUnifiedTopology: true,
    useNewUrlParser: true
});
 
connect();
 
// ESNext syntax using async-await
async function connect() {
    try {
        await client.connect();
        const db = client.db('cars');
        console.log(
    `Successfully connected to db ${db.databaseName}`);
    }
    catch (err) {
        console.error(`we encountered ${err}`);
    }
    finally {
        client.close();
    }
}


Output: 
 

Successfully connected to db cars

Now that we have made the connection, let us see some basic Insertion, Read, Update and Delete Operations on our database: 
Insertion and Read: In the following code snippet we are going to deal with Insertion and Read operation.

JavaScript




const { MongoClient } = require('mongodb');
 
const client = new MongoClient(uri, {
    useUnifiedTopology: true,
    useNewUrlParser: true
});
 
connect();
 
async function connect() {
    try {
        await client.connect();
        const db = client.db('cars');
        console.log(
    `Successfully connected to db ${db.databaseName}`);
 
        const sportsCars = db.collection('SportsCars');
     
        // Insertion
        const cursorInsertion = await sportsCars.insertMany([
            {
                'company': 'mercedes',
                'series': 'Black Series',
                'model': 'SLS AMG'
            },
            {
                'company': 'Audi',
                'series': 'A series',
                'model': 'A8'
            }]);
        console.log(cursorInsertion.insertedCount);
         
        // Display
        const cursorFind = sportsCars.find();
        const data = await cursorFind.toArray();
        console.table(data);
    }
    catch (err) {
        console.error(`we encountered ${err}`);
    }
    finally {
        client.close();
    }
}


Explanation: A collection called sports cars is created using the collections() method. For Insertion, we use the two following methods: 
 

  1. insertMany() method: This method is used to insert more than one entry into the database with the help of cursors. In this case, it takes an array of objects as parameters. The method returns a promise, hence we used the await keyword. Alternatively, the method insertOne() is used to insert a single document into the table.
  2. InsertedCount: This function is used to count the number of insertions that were made.

For Display we used the following methods:

  1. find(): This method is used to find all the documents in the database with the help of cursors.
  2. toArray(): This method uses the cursor element received from the find() method to store the database in an array of objects. This method returns a promise, hence we have used the keyword await.

The Output of the Snippet is as follows:

Update: The following code snippet will help us to update a database element and then we shall display the updated database:

JavaScript




const { MongoClient } = require('mongodb');
 
const client = new MongoClient(uri, {
    useUnifiedTopology: true,
    useNewUrlParser: true
});
 
connect();
 
async function connect() {
    try {
        await client.connect();
        const db = client.db('cars');
 
        const sportsCars = db.collection('SportsCars');
        //update
        const cursorUpdate = await sportsCars.updateOne(
            { "company": "mercedes" },
            { "$set": { "status": "sold" } }
        );
 
        console.log(cursorUpdate.modifiedCount);
         
        // Display
        const cursorFind = sportsCars.find();
        const data = await cursorFind.toArray();
        console.table(data);
    }
    catch (err) {
        console.error(`we encountered ${err}`);
    }
    finally {
        client.close();
    }
}


Explanation: We use the following methods for updating the database:

  1. updateOne() method: This methods allows us to update one entry. The first argument it takes is a key-value pair corresponding to the database entry as we want to update. It can be any of the properties that the element possesses. The second argument is an update command $set, which is paired with an object. The object is again a key-value pair of either an existing or a new property. If the property already exists, then the property is updated with the value passed. If it does not exist, then it is added. This method returns a promise, hence we use the keyword await. Alternatively, updateMany() method can be used to update multiple documents.
  2. modifiedCount: This method is called on the cursor element received from the previous method and gives us a count of the number of entries updated.

Output: 
 

Deleting an Entry: In the following snippet, we will delete an entry based on series:

JavaScript




const { MongoClient } = require('mongodb');
 
const client = new MongoClient(uri, {
    useUnifiedTopology: true,
    useNewUrlParser: true
});
 
connect();
 
async function connect() {
    try {
        await client.connect();
        const db = client.db('cars');
 
        const sportsCars = db.collection('SportsCars');
        //Delete
        const cursorDelete = await sportsCars
                .deleteOne({ "series": "A series" });
 
        console.log(cursorDelete.deletedCount);
         
        // Display
        const cursorFind = sportsCars.find();
        const data = await cursorFind.toArray();
        console.table(data);
    }
    catch (err) {
        console.error(`we encountered ${err}`);
    }
    finally {
        client.close();
    }
}


Explanation: We use the following methods to delete the entry “company” : “Audi” from the database:

  1. deleteOne: This method is used to delete one entry from the database. It takes in a key-value pair which corresponds to the entry that we want to delete. This method returns a promise. Hence, we use the keyword await. Alternatively, deleteMany() method can be used to delete multiple documents at once.
  2. deletedCount: This method is called on the cursor element received from the previous method and it returns the number of deletions that were made.

Output:

Hence, Node and MongoDB can be easily used to make efficient backend CRUD apis.



Last Updated : 15 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads