How to create a CRUD operation using MongoDB and NodeJS?

Muthuramalingam Duraipandi
6 min readMar 18, 2022

--

Introduction:

This story will explain how to create a CRUD operation using MongoDB and Nodejs

Nodejs:-
Node.js is an open-source server-side runtime environment built on Chrome’s V8 JavaScript engine. Node.js is a single-threaded application. It is non-blocking I/O.NodeJS can easily understandable programming. It is an event-driven programming language and Using Nodejs we can create a chat app and content management app and single-page app and etc. It is fully open-source and Nodejs is cross-platform. It can run into Mac, Windows, Linux, and Raspberry pi.

MongoDB:-

MongoDB is a document-oriented open-source NoSQL database .It is a query less . MongoDB is high scalability. here we don’t have a complex chain.it is very easy to learn.

Step 1:

Now we are going to start the node project

npm init 

it will create package.json file .package.json is the heart of nodejs project .it is contain the module version and description and author details.

below I added the project directory structure

Step 2:

Here I am going to add some dependency into app.js

now I am going to add an express module

var express = require(‘express’);

ExpressJS is a middleware framework .why we are using expressJS for mainly routing purposes and it is an intermediate framework. it is intermediate for server to client .

Here We are adding the mongoose module

mongoose module is used for connecting nodeJS to MongoDB .when we are writing mongo query it will make understanding to nodeJS like it will manage between the object to code.

Next, we will add body-parser module

var bodyParser = require(‘body-parser’);

body-parser used for reading objects from REST APIs like JSON and files and URL

Now we are adding HTTP module

var http = require(“http”);

HTTP module is nothing. but it is used to create get, delete and post and put methods

Here we are going to connect MongoDB URI

then here we will create config file for defining MongoDB URL

config.js

{"mongoUri":"mongodb+srv://xyz:xyz@cluster0.kqsgz.mongodb.net/myFirstDatabase"}
mongoose.connect(config.mongoUri+’?retryWrites=true&w=majority’,{ useNewUrlParser: true },(err)=> {if (err){console.log(“MongoDB is not connected”);}else{console.log(“MongoDB is connected successfully”);}});

here app.js

var config = require("./config/dbconfig");
var app = express();
var server = http.createServer(app);
var userRouts = require('./routes/userRoute');
/*Here we are connecting mongodb conection */
mongoose.connect(config.mongoUri+'?retryWrites=true&w=majority',{ useNewUrlParser: true },(err)=> {
if (err){
console.log("MongoDB is not connected");
}else{
console.log("MongoDB is connected successfully");
}
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(function(err, req, res, next) {
res.header("Access-Control-Allow-Origin", "https://www.sandbox.paypal.com");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next(err);
});
app.use("/user",userRouts);
server.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

Step 3:

Here we will create mongodb schema model. now we have one collection so we will create one model into model folder. Schema in mongoose is mapping to mongodb collection.

user.js

var mongoose = require("mongoose");
const userSchema = new mongoose.Schema(
{
name: { type: String, required: true },
age:{type:Number},
role:{type:String},
},
{ collection: 'user' }
)
module.exports = mongoose.model('User', userSchema)

Step 4:

Next we will create middleware function . we used to call controller methods are like find() and create() and remove() and update() and etc.Here we will create method for insert new records into mongodb database.

methods.addUser = (req) => {
return new Promise((resolve, reject) => {
User.create( req.body, (err, docs) => {
if (err){
reject(err);
}
else {
resolve({
status:200,message:"added successfully"
})
}
})
})
}

Step 5:

Here we are going to create get Method for getting existing record from mongodb database. we can use find() method get all information and if we want one record we can use findOne() or inside find we can put conditions.

methods.getUserList = () => {
return new Promise((resolve, reject) => {
User.find({}, (err, docs) => {
if (err){
reject(err);
}
else {
resolve({
status:200,data:docs
})
}
})
})
}

Step 6:

Now we will create update Method for updating existing records from mongodb database . here we can use update() or updateOne() method

methods.updateUser = ( req) => {
return new Promise((resolve, reject) => {
User.updateOne({
_id: ObjectId(req.body._id)
}, {
$set: {
name: req.body.name,
role:req.body.role,
age:req.body.age
}
}, (err, docs) => {
if (err){
reject(err);
}
else {
resolve({
status:200,message:"updated successfully"
})
}
})
})
}

Step 7:

Now we will create a delete method for removing existing records from the database

methods.deleteUser = (userId) => {
return new Promise((resolve, reject) => {
User.remove( {_id:userId}, (err, docs) => {
if (err){
reject(err);
}
else {
resolve({
status:200,message:"deleted successfully"
})
}
})
})
}

here all controller codes attached

userController.js

const methods = {};
const User = require("../models/user");
const { ObjectId } = require("mongoose").Types;
methods.addUser = (req) => {
return new Promise((resolve, reject) => {
User.create( req.body, (err, docs) => {
if (err){
reject(err);
}
else {
resolve({
status:200,message:"added successfully"
})
}
})
})
}
methods.updateUser = ( req) => {
return new Promise((resolve, reject) => {
User.updateOne({
_id: ObjectId(req.body._id)
}, {
$set: {
name: req.body.name,
role:req.body.role,
age:req.body.age
}
}, (err, docs) => {
if (err){
reject(err);
}
else {
resolve({
status:200,message:"updated successfully"
})
}
})
})
}
methods.getUserList = () => {
return new Promise((resolve, reject) => {
User.find({}, (err, docs) => {
if (err){
reject(err);
}
else {
resolve({
status:200,data:docs
})
}
})
})
}
methods.deleteUser = (userId) => {
return new Promise((resolve, reject) => {
User.remove( {_id:userId}, (err, docs) => {
if (err){
reject(err);
}
else {
resolve({
status:200,message:"deleted successfully"
})
}
})
})
}
module.exports = methods;

Step 8:

Now we will create REST API using expressjs into route files for mapping controller to a specific action.

for inserting record create POST API

router.post("/adduser", (req, res) => {
console.log("req.body",req.body);
userController.addUser(req)
.then(data => res.send(data))
.catch(err => res.send(err))
});

here we will create update REST API

router.post("/updateuser", (req, res) => {
userController.updateUser(req)
.then(data => res.send(data))
.catch(err => res.send(err))
});

we will create get record REST API

router.get("/getuser", (req, res) => {
userController.getUserList()
.then(data => res.send(data))
.catch(err => res.send(err))
});

we will create remove record REST API

router.delete("/del",(req,res)=>{
userController.deleteUser(req.params.id)
.then(data => res.send(data))
.catch(err => res.send(err))
})

userRoutes.js

var express = require("express");
var router = express.Router();
var userController = require("../controllers/userController");
router.post("/adduser", (req, res) => {
console.log("req.body",req.body);
userController.addUser(req)
.then(data => res.send(data))
.catch(err => res.send(err))
});
router.post("/updateuser", (req, res) => {
userController.updateUser(req)
.then(data => res.send(data))
.catch(err => res.send(err))
});
router.get("/getuser", (req, res) => {
userController.getUserList()
.then(data => res.send(data))
.catch(err => res.send(err))
});
router.delete("/del",(req,res)=>{
userController.deleteUser(req.params.id)
.then(data => res.send(data))
.catch(err => res.send(err))
})
router.delete("/deleteuser/:id", (req, res) => {

});
module.exports = router;

Step 9:

Now hit the API via postman

POST -> http://localhost:3000/user/adduser

{
“name”:”muthu”,
“age”:26,
“role”:”admin”
}

Once hit API we can check mongoatlas site

All APIs

POST->http://localhost:3000/user/updateUser

{
“name”:”muthu”,
“age”:26,
“role”:”admin”,
“id”:”6234a4b692b6395216790753"
}

GET -> http://localhost:3000/user/getUser

DELETE->http://localhost:3000/user/deleteUser?id=6234a4b692b6395216790753

Thank you for reading

--

--

Muthuramalingam Duraipandi
Muthuramalingam Duraipandi

Written by Muthuramalingam Duraipandi

Software engineer @epsilon , Tech enthusiast, Technical Author, Speaker, Blogger

No responses yet