CRUD app with Node, Express, and MongoDB
Published: 2021-12-24 16:42:31

Let’s clear about some technical words that are used here-

**CRUD:** CRUD stands for Create, Read, Update and Delete. Here-

- C - Create (Post)
- R - Read (Get)
- U - Update (Put)
- D - Delete (Delete)

- Express: Express is a framework to communicate with NodeJS with Database.

- MongoDB: This is a database where we can store our data.

- Node JS: Node.js is an open-source, cross-platform back-end JavaScript runtime environment that uses the V8 engine to execute JavaScript code outside of the web browser.

The whole process of these technologies at a glance in an image.


![node js crud](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tsqa1dvfomjr1fau9t0u.png)

Before starting our CRUD operation using these technologies we must install all required packages-

- NodeJS - From this link, https://nodejs.org/en/download/ download the LTS version and install it.

- MongoDB - “npm i mongodb” using this command line without double quote can install MongoDB.

- Express JS: “npm install express --save” using this command line we can install Express JS.

- Cors: “npm i cors” use this command line

**Now Back To The Code**

```
const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
require('dotenv').config();
const { MongoClient } = require('mongodb');
const ObjectId = require('mongodb').ObjectId;
const cors = require('cors');
```

These codes are used as links with the packages.

```
app.use(cors());
app.use(express.json());

```

This middleware is for connecting with clients and servers.
**Database configuration with MongoDB**

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

```

**Before connecting with the Database must create a .env file to store secret data**

**C - Create (POST) from CRUD**

```
app.post('/order/add', async (req, res) => {
          		const cursor = req.body;
            const result = await orderCollection.insertOne(cursor);
            	res.json(result);        
});
```

Here app.post indicates that this method creates a new record in the database.

**R - Read (GET) from CRUD**

```
app.get('/order', async (req, res) => {
            const cursor = orderCollection.find({});
            const result = await cursor.toArray();
            res.send(result);
        })

```

Here app.get indicates that this method reads all orders from the database.

**U - Update (PUT) from CRUD**

```
app.put('/', (req, res) => {
  		res.send("PUT Request Called")
})
```

Here app.put indicates that this method updates a record from the database.

**D - Delete (DELETE) from CRUD**

       

```
 app.delete('/order/:id', async (req, res) => {
            const id = req.params.id;
            const query = { _id: ObjectId(id) };
            const result = await orderCollection.deleteOne(query);
            res.json(result);
        });
```

Here app.delete indicates that this method deletes a record from the database.