CRUD operation in Node Mongo API Integration
Published: 2021-12-24 14:47:33

CRUD Operations: 
Create: here we created a post request to insert a new service or data into the database. Create is like a postman who takes the data to the database through a node server with a post request. .insertOne() method actually does the work. Example: 

//---------------- Create service --------------//

        app.post('/services', async (req, res) => {
            const service = req.body;
            console.log(service)
            const result = await servicesCollection.insertOne(service);
            res.json(result);
        });

Retrieve: retrieve service or data from the database we use to get a request in the node server. And the get request use the .find() method to find all the data that exist in the database


        //------------------- Retrieve services --------------//

        app.get('/services', async (req, res) => {
            const cursor = servicesCollection.find({});
            const orders = await cursor.toArray();
            res.json(orders);
        });


Delete: when we need to delete data from the database, we use the delete request and the work done by the .deleteOne() method. It deletes specific data by a query.

//-------------------delete service --------------//

app.delete('/orders/:id', async (req, res) => {
            const id = req.params.id;

            const query = { _id: ObjectId(id) }

            const result = await ordersCollection.deleteOne(query);

            res.json(result);
        });

Update:  when we need to change something of existing data we use put request to update the old data. Example :

//----------------UPDATE API---------------------------//
        app.put('/users/:id', async (req, res) => {
            const id = req.params.id;
            const updatedUser = req.body;
            const filter = { _id: ObjectId(id) };
            const options = { upsert: true };
            const updateDoc = {
                $set: {
                    name: updatedUser.name,
                    email: updatedUser.email
                },
            };
            const result = await usersCollection.updateOne(filter, updateDoc, options)
            console.log('updating', id)
            res.json(result)
        })

How to retrieve the latest record from database collection:
 To retrieve the latest record we need two basic functions: 

•	.sort() – It accepts a parameter according to which it sorts the data in descending (-1) or ascending(1) order.
•	.limit() – It decides the number of documents needed to be retrieved.




Example of CRUD operation with full beckend code: 
const express = require('express');
const { MongoClient } = require('mongodb');
const cors = require('cors');
const ObjectId = require('mongodb').ObjectId;

const app = express();
const port = 5000;

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

const uri = uri link here ;

const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function run() {
    try {
        await client.connect();
        const database = client.db('foodMaster');
        const usersCollection = database.collection('users');
        //-------------------- GET API----------------------//
        app.get('/users', async (req, res) => {
            const cursor = usersCollection.find({});
            const users = await cursor.toArray();
            res.send(users);
        });

        app.get('/users/:id', async (req, res) => {
            const id = req.params.id;
            const query = { _id: ObjectId(id) };
            const user = await usersCollection.findOne(query);
            // console.log('load user with id: ', id);
            res.send(user);
        })

        //--------------------------- POST API----------------------------//
        app.post('/users', async (req, res) => {
            const newUser = req.body;
            const result = await usersCollection.insertOne(newUser);
            console.log('got new user', req.body);
            console.log('added user', result);
            res.json(result);
        });

        //---------------------------UPDATE API----------------------//
        app.put('/users/:id', async (req, res) => {
            const id = req.params.id;
            const updatedUser = req.body;
            const filter = { _id: ObjectId(id) };
            const options = { upsert: true };
            const updateDoc = {
                $set: {
                    name: updatedUser.name,
                    email: updatedUser.email
                },
            };
            const result = await usersCollection.updateOne(filter, updateDoc, options)
            console.log('updating', id)
            res.json(result)
        })

        //----------------------------------- DELETE API--------------------------//
        app.delete('/users/:id', async (req, res) => {
            const id = req.params.id;
            const query = { _id: ObjectId(id) };
            const result = await usersCollection.deleteOne(query);

            console.log('deleting user with id ', result);

            res.json(result);
        })
    }
    finally {
        // await client.close();
    }
}

run().catch(console.dir)

app.get('/', (req, res) => {
    res.send('Running my CRUD Server');
});

app.listen(port, () => {
    console.log('Running Server on port', port);
})