How to Install npm Using MongoDB

Learn how to use MongoDB’s Node.js driver with npm to connect with the database and perform CRUD operations.

MongoDB is a modern, general-purpose document database that has been widely paired with Node.js in popular tech stacks such as the MEAN stack (MongoDB, Express.js, AngularJS, and Node.js) and the MERN stack (MongoDB, Express.js, React.js, and Node.js).

npm, Node.js’s package manager, is the bridge that allows the MongoDB Node.js driver to be installed, making it easier for developers to work with MongoDB from inside a Node.js script.

This blog post walks you through the steps needed to connect to a MongoDB database by using npm. To follow along, you will need the following tools:

  • Node

    • Node.js is a JavaScript runtime for building fast and scalable network applications, and it comes with npm installed.

  • MongoDB

    • MongoDB uses documents to store data in an organized way. A document is a field-value pair where the field is a unique identifier pointing to a specific data point. For higher efficiency and optimization, MongoDB represents these documents in a binary-encoded format known as BSON.

  • MongoDB Node.js driver

    • To connect your application with a database, you need a software component, also known as a driver. MongoDB Node.js driver supports database connection, authentication, CRUD operations, and observations, among other features.

  • MongoDB Atlas

    • You can create a database either locally or in the cloud by using MongoDB Atlas, a fully managed cloud database service.

Initialize the Project

Before you install the driver, make sure you have the compatible version of Node.js by running npm --version in your terminal. If you see an error, head over to the Node.js documentation and install the correct Node version.

Next, create a project directory called “node-mongoDB”. Open your terminal and execute the following command:

mkdir node-mongoDB && cd node-mongoDB

Using mkdir, you created a new directory and named it “node-mongoDB” (you could call it anything you want). Using cd, you will move from the current working directory into your newly created directory.

Once inside the directory, create a package.json file by running the following command:

npm init -y

The “y” flag generates an npm package that uses the default values.

Add MongoDB as a Dependency

Next, install the MongoDB driver along with its dependencies by running the following command:

npm install mongodb --save

The “--save” flag saves the driver and its dependencies into a directory called “nodemodules” _in your project directory.

Create a MongoDB Cluster

For this tutorial, you will need a cluster. A cluster—a managed MongoDB service—is a group of servers that store your data. With just a few clicks, you can set up a working MongoDB cluster. Follow these steps to create and connect to a cluster:

Be sure to save the connection string and database user’s username and password for connecting to the database.

Connect to Your Cluster

Next, we connect our application to the newly created database. Inside your directory, create an “index.j” file.

At the top of yourindex.js” file, you need to import the MongoDB driver.

const { MongoClient } = require('mongodb');

The MongoClient is an object used to initiate the connection with the database. To connect to the database, you need a universal resource identifier (URI) that defines the relationship between the application and the MongoDB instance.

After the import:

  1. Create an asynchronous function called main.
  2. Save your URI from earlier in a variable called uri.
  3. Create an instance of MongoClient by passing your connection URI to it, and save it in a variable called mongoClient.
  4. Inside the try/catch block, connect using the connect() method. This will help you handle any unexpected errors.
  5. Using the finally statement, close the connection to the cluster.
  6. After your main() function ends, call it by using main().

Copy and paste the following code after the import:

async function main() {
   const uri = `mongodb+srv://m001-student:<password>@<clustername>.mongodb.net`;
   const mongoClient = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

   try {
       await mongoClient.connect();
       console.log("Connected correctly to server");
   } catch (e) {
       console.error(e);
   } finally {
       await mongoClient.close()
   }
}

main();

Run the command node index.js in your terminal. If everything goes smoothly, you should see a “Connection successful” message logged in your terminal.

CRUD Operations

Now you can select a database by using the db() command. If the database doesn’t exist yet, it will be created.

Our example will create a database called school, which will have a collection of students.

Copy the following code and paste it inside the try block on the main function.

try {
       await mongoClient.connect();
       console.log("Connected correctly to server");
       
       const db = mongoClient.db('school');
       const collection = db.collection('students');
}

Create

Now that you have a database and a collection set up, you can create a new document by using insertOne(). To create a document:

  • Create an asynchronous function called createDocument, and pass collection as a parameter.
  • Inside the function, create an object called studentDocument, and store the student’s information in it.
  • Using await, pass the newly created object as a parameter to insertOne().

Copy and paste the following code after the main function ends.

async function createDocument(collection) {
   let studentDocument = {
       "name": 'John Smith',
       "birth": new Date(1993, 11, 20),
       "address": { "street": 'Pike Lane', "city": 'Los Angeles', "state": 'TN', 'zipcode': '37146' },
   }

   await collection.insertOne(studentDocument);
}

Now that you’ve written the function, you have to call it. Inside the main function’s try block, after you’ve defined the collection, call createDocument.

try {
       ...
       await createDocument(collection);
   }

Run the command node index.js in your terminal. You won’t see any different results in your terminal. Navigate to your MongoDB Atlas, and select collections. Once selected, you should see your newly created database, collection, and document.

Even though you haven’t provided the id field, notice there’s an id field present for your document. This is because if you don’t provide the _id field, the MongoDB driver will automatically create a unique id for the document.

Find

You can use the find() method to retrieve documents from the database. This requires you to pass a query object with optional properties to filter the database. Similar to the createDocument function, you will create a findDocument function.

Copy the following function and add it after the createDocument function.

async function findDocument(collection) {
   const document = await collection.find({ name: 'John Smith' }).toArray();
   console.log(document)
}

Call this function inside the try block on the main function. Make sure to comment out the call to the createDocument function. Otherwise, the call createDocument will create a new document with the same information and a new id.

try {
      ...
       // await createDocument(collection);
       await findDocument(collection);
   }

Run the command node index.js, and you will see the studentDocument object logged in your terminal.

To play around, try updating the name to John and notice what happens.

Update

When you want to update a document, use the updateOne() method. This method has two required parameters:

  • The query selector object that indicates which document needs to be updated.
  • An object indicating what changes need to be applied.
async function updateDocument(collection) {
   await collection.updateOne({ name: 'John Smith' }, { '$set': { 'name': 'Zaki Amani' } })
}

Call this function inside the try block on the main function. Make sure to comment out the call to both the createDocument and the findDocument function.

try {
       ...
       // await createDocument(collection);
       // await findDocument(collection)
       await updateDocument(collection);
   }

Run the command node index.js. Because you aren’t logging anything, you won’t see anything in your terminal, but if you refresh your Atlas, you should see the updated document.

Delete

To remove a document from the database, use the deleteOne() method. This method takes in an object specifying which document to delete as its first parameter.

async function deleteDocument(collection) {
   await collection.deleteOne({ name: Zaki Amani})
}

Call the function inside the try block on the main function, and comment out the previous calls.

try {
      ...
       // await createDocument(collection);
       // await findDocument(collection)
       // await updateDocument(collection);
       await deleteDocument(collection);
   }

Run the command node index.js and refresh the Atlas. You’ll see the document has been deleted.

This tutorial scratches the surface of the MongoDB Node.js driver and Atlas. The MongoDB Node.js driver offers various methods, including but not limited to methods for aggregating, inserting, and replacing documents. You also can use Atlas to distribute and secure your data, build for optimization, and perform other functions.

FAQs

How do you install MongoDB using npm?

To install MongoDB using npm, execute npm install mongodb --save in your root directory. This will download the MongoDB Node.js driver and add a dependency entry in your package.json file.

How can you initialize the MongoDB app npm?

To initialize a MongoDB app, create a new directory and move from the current working directory into the newly created directory. Once inside the directory, you can use npm init -y. The y flag automatically accepts the default values for the command.

mkdir node-mongoDB && cd node-mongoDB
npm init -y

How do you install MongoDB in Windows using npm?

To install MongoDB in Windows using npm, execute npm install mongodb --save in your root directory. This will download the MongoDB Node.js driver and add a dependency entry in your package.json file.

How do you install MongoDB on Mac using npm?

To install MongoDB on Mac using npm, execute npm install mongodb --save in your root directory. This will download the MongoDB Node.js driver and add a dependency entry in your package.json file.

Can you use npm MongoDB without downloading from the MongoDB website?

Yes, you can use npm MongoDB by executing the command npm install mongodb. This command downloads the official MongoDB driver for Node.js and the dependencies required for its installation.

How do you run MongoDB with Node.js?

Once you’ve got MongoDB installed, you first want to import MongoClient at the top of your file. Once you’ve imported, create a new MongoClient instance and pass your connection string as a parameter. Then, using your connect method, you can connect and work with your data. For more details, follow this tutorial.

What is Node.js?

MongoDB Node.js driver is an interface through which your Node.js applications can connect and communicate with MongoDB. The driver features an asynchronous API that allows your Node.js applications to work with data.

How do I start MongoDB in Node.js?

Follow these steps to start MongoDB:

  • Install the MongoDB driver, using npm.
  • Import MongoClient at the top of your file.
  • Create a new MongoClient instance and pass your connection string as a parameter.
  • Connect by using the connect method.

    For more details, follow this tutorial.

What does npm stand for?

npm stands for Node Package Manager. npm is an open source project that helps developers easily share packages. It also offers a command-line client that allows developers to install and publish these packages.

What is npm update?

npm update is a command that updates all modules present in package json to their latest versions. Use npm update followed by the package name to update the package. For example, to update MongoDB, you can use npm update mongodb.

What is the difference between npm and Node?

Node.js is a JavaScript runtime built on Google Chrome’s V8 JavaScript engine. On the other hand, npm is a tool that allows users to install third-party libraries.

Are npm packages free?

According to the policies, using npm Open Source is free.

Can npm update itself?

To update npm to the latest version, you can run npm i -g npm@latest. To update npm to a specific version, you can run npm i -g npm@x.x.x.

Is npm the same as npm install?

npm is a node package manager, whereas npm install is a command for installing these packages.