Crud Operation Using MongoDB And NodeJS

In this article, we will learn about how we can perform crud operation in Node.js using MongoDB.

— First of all, create a src folder in your project.

— Then install a express and mongoose npm

  • $npm install express
  • $npm install mongoose

— Create a  database/db.js file and add the below code there.

onst mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/student', { //student is database name
    useNewUrlParser: true,
}, (err) => {
    if (!err) {
        console.log('conected with mongodb')
    } else {
        console.log('Error in DB connection: ' + err)
    }
});

–Create a models/models.js file and create the schema.

const mongoose = require('mongoose');
var studentSchema = new mongoose.Schema({
    name: {
        type: String,
    },
    email: {
        type: String
    },
    city: {
        type: String
    }
})
const studentDetail = mongoose.model('studentdetails', studentSchema); //studentdetails collection
module.exports = { studentDetail}

–Create a controller/stuController.js file and perform the operation.

const {studentDetail} = require('../models/models');


/* insert student */
exports.addStudent = async (req, res) => {

    let data = await new studentDetail(req.body).save()
    
    res.status(200).send({
        isSuccess: true,
        data:data
    });
}

/* edit student */
exports.editStudent = async (req, res) => {
    await studentDetail.updateOne({ _id: req.body.id }, { name: req.body.name, email: req.body.email });
    res.status(200).send({
        isSuccess: true,
        message:"record updated successfully"
    });
}

/* delete student */
exports.removeStudent = async (req, res) => {
    await studentDetail.remove({ _id: req.body.id })
        .then(re => {
            res.status(200).send({
                isSuccess: true,
                message:"record removed successfully"
            });
        })
        .catch(err => {
            res.status(200).send({
                isSuccess: false,
                error: err
            });
        })
}

/* show */
exports.showStudent = async (req, res) => {
    await studentDetail.find()
        .then(re => {
            res.status(200).send({
                isSuccess: true,
                data:re
            });
        })
        .catch(err => {
            res.status(200).send({
                isSuccess: false,
                error: err
            });
        })
}

— After create the stuController.js  file add a route in the router/router.js file

const express = require('express');
const route = express.Router();
const moddelController = require('../controller/stuController');

route.post('/addstudent',moddelController.addStudent)
route.post('/editstudent',moddelController.editStudent)
route.delete('/removestudent',moddelController.removeStudent)
route.get('/showstudent',moddelController.showStudent)
module.exports = route;

— In the root directory add a app.js file.

const express = require('express')
const app = express()
const port = 5000
const db = require('./src/database/db');
const route = require('./src/router/route');
app.use(express.json())
app.use(route)

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Add Student : insert student record in studentdetails collection

output:

Edit Student: update student record using specific student id

output:

Delete Student: remove the student record using id

–Get All Student: show all the record from studentdetails schema

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories