DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for CRUD operation with Expressjs and MongoDB
Md. Imran Hossain
Md. Imran Hossain

Posted on • Updated on

CRUD operation with Expressjs and MongoDB

We will create a CRUD(create, read, update and delete) application in this article with expressand MongoDB. You need to have basic understandings of MongoDB, express.js, javascript, and node package manager (npm) to install some packages. At the end of this tutorial, we will be able to create CRUD API’s.

I will use Postman to send the HTTP requests to the API created by this application. Before dive in, make sure your computer has node installed

Installations of necessary packages:
At first, we need to go to our command terminal and run following commands:

mkdir crud-operation
cd crud operation
npm init -y
Enter fullscreen mode Exit fullscreen mode

These will create a folder name crud-operation and install necessary node packages
Now, install nodemonusing this command

npm install -g nodemon
Enter fullscreen mode Exit fullscreen mode

nodemonis a tool that helps develop node.js-based applications by automatically restarting the node application when file changes in the directory are detected. This way we won’t have to start the server manually after a change in the index.js(we will talk about it later)

We will need some more packages to install

npm install dotenv cors mongodb express
Enter fullscreen mode Exit fullscreen mode

dotenv is used to access the environment variables and cors is required to share cross origin resources.
Create index.js file in the root directory of the application.
Add the following two lines in the scripts object of package.json file.

 "start": "node index.js",
 "start-dev": "nodemon index.js",
Enter fullscreen mode Exit fullscreen mode

So the basic configuration is completed. Now we will populate our index.js file to create our first-ever API.

const express = require('express')
const app = express()
const port = 5000

//middleware goes here section

app.get('/', (req, res) => {
    res.send('Hello World!')
})

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})
Enter fullscreen mode Exit fullscreen mode

Run npm run start-dev command in the terminal. I am using postman to load the HTTP request. So place this link http://localhost:5000/ in the get request. Congratulation! It will display the http response.

hello world!

The Postman API response will be like so.
Image description

Now, Let’s decode the above code. We essentially get an express instance and assign it to app. The server needs a port to load to API response, we used port 5000. Then we created a get request in the root URL ( β€˜/’ means http://localhost:5000/). The get request in reply gives us a response which is β€˜hello world’. To access the server port 5000, we used the listen method which takes the port as the first argument and a callback function as second argument.

Create a MongoDB account unless you have one. Add a user in the database access section. Put the user name and password in the .env file. Set ip address to 0.0.0.0/0 in the network access section. Add the following in the index.js file.

const { MongoClient } = require('mongodb');
require('dotenv').config()
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.krune.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function run() {
    try {
        await client.connect();
        const database = client.db("CRUD");
        const blogsCollection = database.collection("blogs");

         //CRUD API’s goes here   
    } finally {
        // await client.close();
    }
}
run().catch(console.dir);
Enter fullscreen mode Exit fullscreen mode

We have imported the MongoDB client. MongoDB gives us a connection uri to connect with MongoDB and using the username and password previously stored in the .env file, the uri string is updated. A database and a collection of the database are also created in the run function.

So far we have covered the basic building blocks to start an express app.
Now, we will create CRUD API’s.

Insert Data(create):
Add app.use(express.json()) in the "middleware goes here" section, and add following codes in the "CRUD API goes here" section.

app.post('/blogs', async (req, res) => {
    const blog = req.body
    const result = await blogsCollection.insertOne(blog);
    res.json(result)
})
Enter fullscreen mode Exit fullscreen mode

There are lots of HTTP request methods i.e. GET, POST, PUT, PATCH, DELETE. To create data, we use post method. The first argument is the request API and the callback function is used to perform the create operation. The callback function also take two arguments 1. req(the API request) 2. res(response of the API from server)
The post data(i.e. Form data) from the request is assigned to the blog variable. The request body by default is a JSON object, to convert the JSON object into plain object, we need to use a middleware app.use(express.json()).
insertOne method is used to add the parsed request data to insert the blogCollection. In the end, the response of the api is sent through res.json(result).

If the data is inserted, the response will be 200 like so,

Image description

Find data : (Read)
Get all blogs:

app.get('/blogs', async (req, res) => {
    const query = {};
          const cursor = blogsCollection.find(query);
          const result = await cursor.toArray();
           res.json(result)
        })
Enter fullscreen mode Exit fullscreen mode

Now we use the get method and the URL is the same as the post method. As we want to get all the data, the query is empty, and the find method is used to fetch all the data. The fetched data is converted into an array and sent as a response.
The postman response will be like so,

Image description

Find a single blog:
First we need to add const ObjectID = require('mongodb').ObjectID at the top.

app.get('/blogs/:id', async (req, res) => {
     const blogId = req.params.id;
     const query = { _id: ObjectID(blogId) };
     const result = await blogsCollection.findOne(query);
     res.json(result)
   })
Enter fullscreen mode Exit fullscreen mode

To find a single blog we have passed the id parameter to the API and the parameter is accessed by req.params.id. Now we have to match the blogId to the id of blogs of the server. The result is sent as a response. The ObjectId is required to match the id to blogId.
The postman response will be like so,
Image description

Update:(put method)

app.put('/blogs/:id', async (req, res) => {
      const blogId = req.params.id;
      const blog = req.body;
      const filter = { _id: ObjectID(blogId) };
      const updateBlog = {
            $set: {
                title: blog.title,
                body: blog.body
               },
            };
      const result = await blogsCollection.updateOne(filter, updateBlog);
      res.json(result)
})
Enter fullscreen mode Exit fullscreen mode

At first, we make a query to find the id we want to update using the api params and fetched the data that needs to be updated. The update fields are set and updateOne method is used to update the data.
Postman response will be like so,

Image description

Delete:

app.delete('/blogs/:id', async(req,res)=>{
      const blogId = req.params.id;
      const query = { _id: ObjectID(blogId) };
      const result = await blogsCollection.deleteOne(query);
      res.json(result)
 })
Enter fullscreen mode Exit fullscreen mode

β€˜Delete’ method is used to delete a document from the database. Using the parameter, query is made and then deleteOne method is used to delete that. Finally, the response result is sent as JSON.
The postman response will be like so,

Image description

So that’s pretty much it. This way we can perform CRUD operation with node and MongoDB.
See codes at Github

Top comments (0)

πŸŒ–πŸŒ—πŸŒ˜ Turn on dark mode in Settings