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

Cover image for CRUD app with Node, Express, and MongoDB
Md. Mizanur Rahaman
Md. Mizanur Rahaman

Posted on

CRUD app with Node, Express, and MongoDB

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

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');
Enter fullscreen mode Exit fullscreen mode

These codes are used as links with the packages.

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

Enter fullscreen mode Exit fullscreen mode

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 });

Enter fullscreen mode Exit fullscreen mode

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);        
});
Enter fullscreen mode Exit fullscreen mode

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);
        })

Enter fullscreen mode Exit fullscreen mode

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")
})
Enter fullscreen mode Exit fullscreen mode

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);
        });
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)

Tired of sifting through your feed?

Find the content you want to see.

Change your feed algorithm by adjusting your experience level and give weights to the tags you follow.