NodeJs CRUD Operation Using MongoDB And Mongoose
REST API stands for “ Representational State Transfer Application Programming Interface. ” API uses the URLs to address the resources.API work like a mediator helps us to talk between the server and the client-side. API created on the server. REST decides how the API looks like. We can send a request through URL and get the data in return which is called the response.
CRUD operation means the basic Create Read Update Delete operation. Here, we are going to learn the crud operation of MongoDB.
Let’s start creating the CRUD API’s
Step-1: Set up directories
First, create the base folder(application) which contains all project-related directories. Now create the src folder which contains the server-side specific file.
Check out my previous blog for learn to set up project from scratch.
So the basic project setup will look like this
Step-2: Initialize App
First, for initializing the app run the below command in the terminal.
$ npm init -y
Second, Install the required dependencies.
$ npm install express mongoose validator body-parser nodemon
- Express: Express is used as a web application framework.
- Mongoose: The mongoose is used to connect the database with our project.
- Validator: This library validates and sanitizes strings only.
- Body-parser: Extract the entire body portion of an incoming request stream and exposes it on
req.body
. - Nodemon: This tool is used to automatically restart the server when the change detected.
So this is how your package.json will look like.
Step-3: Configure the Database
Mongoose makes it easier to model our data. This includes data sanitization, data validation, and more. Mongoose has a connection function mongoose.connect() which we are using for connecting our application project with MongoDB.
First, we have to create the file ./src/db/mongoose.js under the root project.
Now we have to require the mongoose module and then declare the MongoDB URL for the connection
const mongoose = require('mongoose')MONGO_URL = 'mongodb://127.0.0.1:27017/app'mongoose.connect(MONGO_URL, () => {
console.log("Database Connected!")
}
Step-3: Modelling the Data
The main feature of Mongoose is to model our data. In one application you can create different models for different types of collections of data. We can create numerous models for our application.
First, create ./src/models/user.js & import the required modules.
const mongoose = require('mongoose')
const validator = require('validator')// Here we defining our Schema(Structure of our collection).const userSchema = mongoose.Schema({
name: {
type: String,
trim: true,
required: true,
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
phone_number: {
type: Number,
required: true,
},
age: {
type: Number,
required: true
}
const User = mongoose.model('User', userSchema)module.exports = User
Create API
For creating the REST API POST HTTP method is used. The URL structure is /endpoint. If we wanted to create a user, it would be POST /create-user. Here ‘create-user’ is an endpoint.
For this first create the route file ./ src/router/user.js up to the root project.
Now we route the request in the router file.
$ npm i expressconst express = require('express')const router = express.Router()//Create User
router.post('/create-user', AuthController.createUser)
...
For controlling the logic create the controller file ./ src/controller/user.js.
const UserModel = require('../models/user.js');class AuthController {
static createUser = async (req, res) => {
try {
const user = new User(req.body);
await user.save()
if(user) {
res.status(200).send({
status: 200,
user
}) } } catch (error) {
res.status(500).send({
status: 500,
message: error.message })
} }}module.exports = AuthController;
Start the server
Now we are going to create the main file of our project (index.js).
We have to require all files in index.js because it handles our application startups and all other functions.
const express = require('express')
const bodyParser = require('body-parser')
const userRouter = require('./router/userRouter')
require('./db/mongoose')const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true})app.use(userRouter)const port = process.env.PORT || 3000;app.listen(port, ()=> {
console.log('Server is up to '+ port)
})
Test API
We have to send the data in the JSON form through the JSON body of the postman.
If your code correctly then you will get the status 200 OK and the result as follow.
Read API
For creating the REST API GET HTTP method is used. The URL structure is /endpoint. If we wanted to get all users, it would be GET /read-users. Here ‘read-users’ is an endpoint.
For this first create the route file ./ src/router/user.js up to the root project.
Now we route the request in the router file.
$ npm i expressconst express = require('express')const router = express.Router()//Create User
router.get('/read-user/:id', AuthController.getAllUsers)
...
For controlling the logic create the controller file ./ src/controller/user.js.
...static getAllUser = async (req, res) => { const _id = req.params.id // retrieve the id provided
User.findById(_id).then((user) => {
if (!user) {
return res.status(404).send({
message: "User Not Found"
})
}
res.send(user)
}).catch((e) => {
res.status(500).send()
})
});
}
Start the server
Start the server the same as we started on Create API
Test API
If your code correctly then you will get the status 200 OK and the result as follow.
Update API
For creating the REST API PATCH HTTP method is used. The URL structure is /endpoint. If we wanted to get all users, it would be PATCH /update-user/:id.
Now we route the request in the router file.
...//Create User
router.patch('/update-user/:id', AuthController.updateUsers)
...
For controlling the logic create the controller file ./ src/controller/user.js.
...static updateUser = async (req, res) => {try {
const user = await User.findByIdAndUpdate(req.params.id,
req.body,
{new: true, runValidators: true})
if (!user) {
return res.status(404).send({
message: "User not found"
})
}else {
res.send(user)
}
} catch (e) {
res.status(400).send(e)
}
}
...
Start the server
Start the server the same as we started on Create API
Test API
We have to send the data in the JSON form through the JSON body of the postman.
If your code correctly then you will get the status 200 OK and the result as follow.
Delete API
For creating the REST API DELETE HTTP method is used. The URL structure is /endpoint. If we wanted to get all users, it would be DELETE /delete-user/:id.
Now we route the request in the router file.
...//Create User
router.delete('/delete-user/:id', AuthController.deleteUsers)
...
For controlling the logic create the controller file ./ src/controller/user.js.
...static deleteUser = async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id)
if (!user) {
return res.status(404).send({
message: "User Not Found"
})
}
res.send(user)
} catch (e) {
res.status(500).send({
status: 500,
message: e.message
})
}
}
...
Start the server
Start the server the same as we started on Create API
Test API
If your code correctly then you will get the status 200 OK and the result as follow.
Summary
In this blog, we have learned to write the code for CRUD operation in NodeJs using MongoDB and Mongoose. CRUD operation stands Create Read Update Delete operation. Here, we learn the crud operation of MongoDB. We create an API for creating a user and get all users after that we create an API to update the data in the existing user and in the last we create an API to delete the user.
For the reference of the above code
Feel free to connect with us read more articles from Aeologic.com.
Aeologic Technologies is a dynamic, solution, and value-driven technology company. We position ourselves as a new generation cutting edge technology company. We work creatively to enable businesses with leading technologies and solutions. You can connect with us on Facebook, Twitter, and LinkedIn for any queries.