Node.js is the most widely used JavaScript framework. It is well-known for offering a high speed to application developers. Most Node.js developers prefer using NoSQL databases to store their data during development. The reason is that NoSQL databases can keep up with the high speed offered by Node.js while at the same time giving the application a high performance. Using Node Js with MongoDB CRUD is a combination that is very powerful.

Although there are many NoSQL databases, MongoDB is a perfect fit for use with Node.js. It offers its users a fast development cycle and efficient performance. Thus, a combination of Node.js and MongoDB forms a powerful technology stack. When using these two technologies, you will need to run operations that modify your MongoDB data from Node.js. CRUD operations are a good example of such operations. The good news is that these two technologies allow you to implement these operations with much ease. In this article, we will be discussing how to run Node Js with MongoDB CRUD operations. 

Prerequisites

This is what you need for this article:

Node JS with MongoDB CRUD: mongodb logo
  • MongoDB – to learn more about MongoDB click here.
Node JS with MongoDB CRUD: node js
  • Node.js – to learn more about Node.JS click here.
Node JS with MongoDB CRUD: curl

Node JS and MongoDB CRUD Operations

In this section, we will be discussing how to run MongoDB CRUD operations from Node.js. 

Streamline Your MongoDB Integration with Hevo

Effortlessly manage and migrate your MongoDB data with Hevo. Hevo supports MongoDB as one of its 150+ data sources, ensuring seamless data integration and real-time synchronization.

  • No-Code Solution: Easily connect and manage your MongoDB data without writing a single line of code.
  • Flexible Transformations: Use drag-and-drop tools or custom scripts for data transformation.
  • Real-Time Sync: Keep your destination data warehouse updated in real time.
  • Auto-Schema Mapping: Automatically handle schema mapping for a smooth data transfer.

Join over 2000 satisfied customers, including companies like Voiceflow and Playtomic, who trust Hevo for their data integration needs. Check out why Hevo is rated 4.7 stars on Capterra.

Get Started with Hevo for Free

1. Node JS with MongoDB CRUD Operations: MongoDB and Node.js Setup

Your computer should be installed with MongoDB and Node.js and a command line with curl command. Download MongoDB MSI package from its official website and run it to install MongoDB. After the installation, run the mongo command to ensure that MongoDB is running. 

Next, ensure that both MongoDB and npm are installed on your computer. You can download Node.js from its official website and install it on your computer. Curl will help you to run HTTP requests on the command line. 

2. Node JS with MongoDB CRUD Operations: Create a New Node.js Project

Open the folder where you will create a project and type the following command:

npm init

Give the project the name node-mongo and accept defaults for the other settings. Add the necessary dependencies to the project. Run the following command within the project directory:

npm install mongodb polka --save

The above command will install the Node.js driver for MongoDB and the Polka HTTP Server to handle HTTP requests. Add the following start script to the package.json file:

Create a /node-mongo/src/index.js file and add the following contents to it:

const polk= require('polka');
polk()
  .get('/create', (req, res) => {
    res.end(`It works`);
  })
  .listen(3000, err => {
    if (err) throw err;
    console.log(`> localhost:3000`);
  });

Now, run the following command to start the server:

npm run start

Test the server by running the following command:

curl http://localhost:3000/create

3. Node JS with MongoDB CRUD Operations: Inserting a Record into GridDB

We need to perform an insert, which is the C in CRUD. Change your index.js file to the following:

const polk = require('polka');
const { MongoClient } = require("mongodb");

polk()
  .get('/create', (req, res) => {
    const cl = new MongoClient("mongodb://localhost:27017");
    async function run() {
      try {
        await cl.connect();
        const dbs = client.db("intro");
        const coll = dbs.collection("quotes");

        const rest = await coll.insertOne({"quote":"This is my quote."});
        res.end(JSON.stringify(rest));
      } catch (ex) {
        console.log("Error: " + ex);
      } finally {
        await cl.close();
      }
    }
    run().catch(console.dir);
  })
  .listen(3000, err => {
    if (err) throw err;
    console.log(`> localhost:3000`);
  });

The above script is an example of a node js with MongoDB crud operation. It establishes a connection to a MongoDB instance, selects a database named intro and a collection named quotes. It then inserts a document into the collection and returns the results as an HTTP response.

To run the insert, press Ctrl+C to stop and restart the node. Next, run the following command on the terminal:

npm run startcurl http://localhost:3000/create
Integrate MongoDB to Snowflake
Integrate MongoDB to Redshift
Integrate MongoDB to BigQuery

Verifying Insert

If you have experience with SQL, you’ll notice that we didn’t first construct a table and schema before beginning this task. Even the database we used wasn’t anything we made. All of this is taken care of by MongoDB, which can add any type of structured key-value document to the collection.

Enter the command use intro in the mongo shell after starting it up. This goes to the automatically generated introduction database. You may verify that the record was inserted by using the db.quotes.find() command right away. You’ll see that MongoDB created a special ID on the “_id” field automatically. This can be changed by putting your own specification on the document.

4. Node JS with MongoDB CRUD Operations: Retrieving from MongoDB

We can use the .get() method to retrieve a document from MongoDB. The following script demonstrates this:

.get('/retrieve', (req, res) => {
    const cl = new MongoClient("mongodb://localhost:27017");
    async function run() { 

      try {
        await cl.connect();
        const dbs= client.db("intro");
        const coll = dbs.collection("quotes");

        const cur = coll.find({}, {});

        let items = [];
        await cur.forEach(function(doc){
          items.push(doc);
        });
        res.end(JSON.stringify(items));
      } catch (err){
        console.warn("ERROR: " + err);
        if (errCallback) errCallback(err);
      } finally {
        await cl.close();
      }
    }
    run().catch(console.dir);
  })

We have used the find command and passed to it an empty query. This means that it will match all documents in the collection. The response is then returned to the client in the form of an array.

After stopping and restarting the server, test the new endpoint with curl http://localhost:3000/retrieve to see if the collection is returned.

5. Node JS with MongoDB CRUD Operations: Updating MongoDB Documents

In this section, we will demonstrate how to update MongoDB documents, which is the “U” in CRUD:

.get('/update', (req, res) => {
    const cl = new MongoClient("mongodb://localhost:27017");
    async function run() {
      try {
        await cl.connect();
        const dbs = client.db("intro");
        const coll = dbs.collection("quotes");

        const updateDocument = {
          $set: {
            author:
              "Martin Kings",
          },
        };

        const rst = await coll.updateOne({}, updateDocument, {}); 
        res.end("Updated: " + rst.modifiedCount);
      } catch (ex) {
        errCallback(ex);
      } finally {
        await cl.close();
      }
    }
    run().catch(console.dir);
  })

In the above node js with MongoDB crud operation, we have connected to the database and created an updated document. We have then changed the author field to Martin Kings. The updateOne() function helped us to execute the update. Since we wanted to match all documents, the filter is empty.

The update doc is then carried out by the aforementioned code using the updateOne() function. The filter is the last empty-object argument. We leave it blank since we want to match on all documents in this instance.

Finally, we reply with the total quantity of modified documents (one).

6. Node JS and MongoDB CRUD Operations: Deleting MongoDB Documents

The following script demonstrates how to delete a MongoDB document from Node.js:

.get('/delete', (req, res) => {
    const cl = new MongoClient("mongodb://localhost:27017");
    async function run() {
      try {
        await cl.connect();
        const dbs = cl.db("intro");
        const coll = dbs.collection("quotes");
        const qry = { };
        const rst = await coll.deleteOne(qry);
        if (rst.deletedCount === 1) {
          res.end("One document deleted.");
        } else {
          res.end("No document was deleted.");
        }
      } finally {
        await cl.close();
      }
    }

We have used an empty query so as to match all the documents within the collection. The deleteOne() function tells us the number of documents that have been deleted. 

Ctrl-C the server to restart it, then run another curl command:

curl http://localhost:3000/delete

That is how to run node js with MongoDB crud operations. 

Learn More About:

NoSQL CRUD Operations Made Easy

Conclusions

This is what you’ve learned in this article:

  • Node.js is the most widely used JavaScript framework. This can be attributed to its high speed and performance. 
  • Node.js developers prefer using  NoSQL databases for data storage during application development due to their high speed and performance. 
  • MongoDB is the best NoSQL database to use with Node.js. It can keep up with Node.js speed and give high performance to the application. 
  • Node.js has a MongoDB driver that one can use to connect to their MongoDB database. This driver can be installed using npm (node package manager). 

MongoDB and PostgreSQL are trusted source that a lot of companies use as it provides many benefits but transferring data from it into a data warehouse is a hectic task. The Automated data pipeline helps in solving this issue and this is where Hevo comes into the picture. Hevo Data is a No-code Data Pipeline and has awesome 150+ pre-built Integrations that you can choose from.

Hevo can help you Integrate your data from numerous sources and load them into a destination to Analyze real-time data with a BI tool such as Tableau. It will make your life easier and data migration hassle-free. It is user-friendly, reliable, and secure.

FAQs

Can I use MongoDB with Node.js?

Yes, MongoDB can be used with Node.js. The official MongoDB driver for Node.js, mongodb, allows you to connect to MongoDB and perform operations. You can also use Mongoose, an ODM (Object Data Modeling) library, to simplify interactions with MongoDB.

How to query MongoDB using Node.js?

Install the MongoDB driver or Mongoose via npm: npm install mongodb or npm install mongoose.
Connect to your MongoDB database.
Use methods like find(), findOne(), and aggregate() to query your data.

Does MongoDB support CRUD?

Yes, MongoDB supports CRUD operations:
Create: insertOne(), insertMany()
Read: find(), findOne()
Update: updateOne(), updateMany()
Delete: deleteOne(), deleteMany()

Nicholas Samuel
Technical Content Writer, Hevo Data

Nicholas Samuel is a technical writing specialist with a passion for data, having more than 14+ years of experience in the field. With his skills in data analysis, data visualization, and business intelligence, he has delivered over 200 blogs. In his early years as a systems software developer at Airtel Kenya, he developed applications, using Java, Android platform, and web applications with PHP. He also performed Oracle database backups, recovery operations, and performance tuning. Nicholas was also involved in projects that demanded in-depth knowledge of Unix system administration, specifically with HP-UX servers. Through his writing, he intends to share the hands-on experience he gained to make the lives of data practitioners better.