• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:9 mins read
You are currently viewing Working with MongoDB Node js Driver

In this article, we will connect to MongoDB from the Node js by installing and using the driver and performing some operations. When MongoDB is combined with Node.js, it becomes an effective tool for creating quick and scalable applications.

Advertisements

Related: MongoDB pymongo Python Package

Pre-requisites: Have MongoDB and npm installed on your system.

1. Install MongoDB driver in node js

As a first step, install the MongoDB database and npm on your system, if they are not already installed. The second step is to download the MongoDB driver for Node.js and install it, we can install it using the npm command of Node.js.

Related: MongoDB Beginners Tutorial with Examples

The npm is a command-line tool that comes with Node.js for installing and managing packages (libraries) in a Node.js project. Here, we use the npm command to install the MongoDB driver.


# Install mongodb driver
npm install mongodb --save

When the --save option is used, the installed package is saved as a dependency in  package.json file by npm. By running the above command you should see output something like the below.

connect MongoDB with the Node.js

2. Create the Directory

After the installation of the mongodb package to package.json, we have to create the directory where the MongoDB program will reside. These are the basic and simple commands which help us to create the directory using the command prompt.


# Create directory
mkdir newProject

Here, we named the directory newProjects and then used the following command to get into that directory.


# Getting into directory
cd newProject

Then, we used the command that initializes a new Node.js project with default values without prompting the user for any configuration options. The command is specified below.


# Initialize a new Node.js project
npm init -y

Here, the init option initializes a new Node.js project by creating a package.json file, and option –y tells npm to use the default values for all the configuration options instead of prompting the user for input. It then gives the following output with a minimal set of properties, such as the project name, version, description, and entry point.

connect MongoDB with the Node.js

3. Connect MongoDB with the Node.js

Finally, we can connect to the MongoDB server using the node js here. The MongoClient class allows us to establish a database connection. The code to connect to a MongoDB database is provided below.


# Connection to MongoDB
const { MongoClient } = require('mongodb');
const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);
const dbName = 'MyDatabase';
async function main() {
  await client.connect();
  console.log('Connected successfully to server');
  const db = client.db(dbName);
  const collection = db.collection('student');
  return 'done.';
}

main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close());

The above program connects to a MongoDB server running on the local machine at port 27017 using the MongoDB Node.js driver. Here, the MongoClient is imported from the mongodb module and is used to connect to the MongoDB server. The url variable holds the connection string to the MongoDB server, and the dbName variable holds the name of the database to connect to.

Then, the main function is declared as an async function that is responsible for establishing a connection to the MongoDB server and performing some operations on the student collection. Hence, the main function returns the string done. When the file.js file is executed, it shows that the operations were successful.

4. Insert New Documents

Now, let’s insert some documents into the MongoDB collection from Node.js, to do insert I have used the main() method with insertMany() in file.js.


# Inserting document in Node.js
async function main() {
  const insertDocuments = 
   await collection.insertMany([{ name: 'John', age: 20 },
                                 { name: 'Billy', age: 25 }, 
                                { name: 'Elena', age: 23 }]);
console.log('Inserted documents =>', insertDocuments);
  return 'done.';
}

Here, we have inserted multiple documents into the student collection using the insertMany() method of the MongoDB Node.js driver. The await option specifies waiting for the insertion operation to complete before continuing with the execution of the code. Thus, the output contains information about the insertion operation which includes the total number of documents inserted and the IDs of the inserted documents.

connect MongoDB with the Node.js

Next, we performed another operation of MongoDB in the Node.js driver which is an update operation. The following code updates the document of MongoDB collection in Node.js. Similarly, you can also perform MongoDB Update Field using Value from Another Field.


#Updating documents
async function main() {
  const updateDocument = await collection.updateOne({ name: 'John' },
                                                  { $set: { age: 22 } });
  console.log('Updated document =>', updateDocument);
  return 'done.';
}

Here, the code changes a single document in the student collection using the updateOne() method of the MongoDB Node.js driver. As we can see the output contains the number of documents matched and the number of documents updated.

connect MongoDB with the Node.js

Additionally, if you want to remove the file from the document in the MongoDB collection, you can follow this link.

6. Conclusion

In conclusion, using mongodb driver with Node.js allows us to connect and run queries on MongoDB database. This driver provides ease of use, scalability, and performance to work with the MongoDB database. I hope you enjoyed learning how to connect to MongoDB from Node js by using mongodb driver.

You can also follow this link to connect MongoDB with the Node.js

Related Articles