Node JS with MongoDB CRUD Operations: 6 Easy Steps

on CRUD, Database Management Systems, MongoDB, Node js • February 17th, 2022 • Write for Hevo

Node JS with MongoDB CRUD - FEATURED IMAGE

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. 

Table of Contents

Prerequisites

This is what you need for this article:

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

Node JS and MongoDB CRUD Operations

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

Simplify Data Analysis with Hevo’s No-code Data Pipeline

Hevo Data, a No-code Data Pipeline helps to load data from any data source such as Databases, SaaS applications, Cloud Storage, SDKs, and Streaming Services and simplifies the ETL process. It supports 100+ data sources (including 30+ free data sources) like Asana and is a 3-step process by just selecting the data source, providing valid credentials, and choosing the destination. Hevo not only loads the data onto the desired Data Warehouse/destination but also enriches the data and transforms it into an analysis-ready form without having to write a single line of code.

GET STARTED WITH HEVO FOR FREE[/hevoButton]

Its completely automated pipeline offers data to be delivered in real-time without any loss from source to destination. Its fault-tolerant and scalable architecture ensure that the data is handled in a secure, consistent manner with zero data loss and supports different forms of data. The solutions provided are consistent and work with different BI tools as well.

Check out why Hevo is the Best:

  • Secure: Hevo has a fault-tolerant architecture that ensures that the data is handled in a secure, consistent manner with zero data loss.
  • Schema Management: Hevo takes away the tedious task of schema management & automatically detects the schema of incoming data and maps it to the destination schema.
  • Minimal Learning: Hevo, with its simple and interactive UI, is extremely simple for new customers to work on and perform operations.
  • Hevo Is Built To Scale: As the number of sources and the volume of your data grows, Hevo scales horizontally, handling millions of records per minute with very little latency.
  • Incremental Data Load: Hevo allows the transfer of data that has been modified in real-time. This ensures efficient utilization of bandwidth on both ends.
  • Live Support: The Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
  • Live Monitoring: Hevo allows you to monitor the data flow and check where your data is at a particular point in time.
SIGN UP HERE FOR A 14-DAY FREE TRIAL

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

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. 

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 100+ pre-built Integrations that you can choose from.

visit our website to explore hevo[/hevoButton]

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.

SIGN UP for a 14-day free trial and see the difference!

Share your experience of learning about Node JS with MongoDB CRUD Operations in the comment section below.

No-code Data Pipeline For Your Data Warehouse