CRUD operations with Node-Express and MongoDB

Fazle Rabbi
3 min readDec 29, 2021

--

Let’s start by introducing the players in a short manner.

Node: Node or formally Node.js is a cross-platform run-time environment to create server-side in JavaScript. So basically Node allows us to use JavaScript as our server-side language.

Express: Express is the most popular Node web framework for building web applications. It helps us to easily create Node web servers.

MongoDB: MongoDB is a NoSQL database to store all the server-side data.

CRUD: CRUD is an acronym that indicates a set of operations.
C for Create, indicates the POST operation.
R for Read, indicates the GET operation.
U for Update, indicates the PUT operation.
D for Delete, indicates the DELETE operation.

Now let’s prepare our server-side. I am not gonna focus on the npm installation process, because that’s the most basic thing and I assume you know that well. Ok, now create a JS file. You can name it index.js, app.js, server.js, or anything you want. Here I’m gonna use “app.js”. Then install Express using the command line-

npm i express

Now import Express and run the server on localhost as the image given below-

That is the most basic set up to run the server on localhost with port 5000.

Now create a database in MongoDB. Keep the username and password to use later. Now connect the MongoDB database to our server. To do that, first, install MongoDB by using the below command line-

npm i mongodb

Then import MongoDB into our app.js file-

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

Then from MongoDB “connect” you can find the codes like the image below-

Copy that code block into our app.js and replace the username and password with those you used when creating the database. At this point, you can console.log the “uri” variable to check the connections.

console.log( uri );

If everything is ok then it should log in to the console without showing any error.

Now create a function to run our operations. Inside the function, we will specify our database and collection, and connect them to the database. Follow the image-

Note that in the finally{} block I have commented out the “client.close()” as it is not needed in our production process for now.

Now we can do our POST, GET, PUT and DELETE operations inside our try block.

You need to use the “ObjectId” to target an item in the collection with its unique id. So use the following line somewhere at the beginning-

const ObjectId = require('mongodb').ObjectId;

Also, you may need to use some middleware of Express to complete the process. The “Cors” is one of them. So, install it using the following command line-

npm i cors

Then add the following line to use it-

app.use(cors());

So this is how we can do the CRUD operations using Node-Express and MongoDB.

Thank you.

--

--

Fazle Rabbi

A dedicated web developer. Loves ReactJS and JavaScript. Enjoys playing with responsive website issues. And always seeks knowledge.