CRUD Operations In Express, Nodejs And MongoDB
Create RESTful API With MongoDB, Express, Node Js - Today we will learn how to create node Js APIs with Mongoose using node js Framework express. Very helpful new backend developer.
This blog may help you to get started, In this tutorial, we will be starting node.js express MongoDB crud creating a server and CRUD (Create, Read, Update and Delete) operations.
How to create Restful API in node js with MongoDB.
So let's get started with it.
Step 1: Setting up the Server
First of all, We need to new express js application Create a new express js application.
Now install Mongoose with NPM. Go to the terminal and use the below commands :
npm i mongoose
Step 2: Database Connectivity mongoose
In this step after setting up the server we will be setting up your database connection, for that, we have to create another file in the root folder db.js with the following content.
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/mongooseCRUD', {useNewUrlParser: true}, (err) => { if (!err) { console.log('Successfully Established Connection with MongoDB') } else { console.log('Failed to Establish Connection with MongoDB with Error: '+ err) } }); module.exports = mongoose;
Here we have required the mongoose module to create CRUD Operations in Express, Nodejs, and MongoDB. Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. Mongoose manages relationships between data provides schema validation and is used to translate between objects in code and the representation of those objects in mongoose crud.
Now run the command node app.js to run your server and making the connection to DB. Also, do not forget to import your DB file in app.js.
Let's move further with our CRUD operation Node.js.
Step 3: Defining the User Model
In this step, we will work on CRUD operation in express, Nodejs, mongoose for a User. So our first step towards it would be defining the model in your project.
To make your code looks clean do make a separate folder for models and create a UserModel.js file in it.
Now we will be defining our node model using mongoose.
const mongoose = require("../db"); const schema = new mongoose.Schema( { email: { desc: "The user's email address.", trim: true, type: String, unique: true, required: true, }, name: { desc: "The user's name.", trim: true, type: String, required: true, }, ); module.exports = mongoose.model("Users", schema);
Now we have created the model in your node.js express MongoDB crud, you can edit the fields according to your needs.
Step 4: Writing Controller functions
After creating the user model we now have to create the user controller file in the controller folder in your project crud operation in nodejs, expressjs, MongoDB.
So we will be defining our CRUD operation Nodejs in this file.
The first function we will be writing a create function for a user.
Creating a User and saving it to the database/** * User controller : All business logic goes here */ router.post("/", async (req, res)=>{ const user= new User({ name: req.body.name email: req.body.email }) try{ let users= await user.save() res.status(200).json({ status: 1, data: users }) } catch(err){ res.status(500).json({ Message:err.message }) } })
/** * Find all Users */ router.get("/", async (req, res)=>{ try{ let users= await User.find(); res.status(200).json(users) } catch(err){ res.status(500).json({ Message:err.message }) } })
Here we are using the find()
function to find all users we can also use the findAll()
function for the same.
/** * Find One Users */ router.get("/:id", async (req, res)=>{ try{ let users= await User.findById(req.params.id); res.status(200).json(users) } catch(err){ res.status(500).json({ Message:err.message }) } })
To find a single user we are finding it by id, we have a function findById()
for the same, we just have to pass the user id in params.
/** * Remove One User */ router.delete("/:id", async (req, res)=>{ try{ let users= await User.findByIdAndRemove(req.params.id); res.status(200).json({ message: "User deleted successfully!", Data: users }) } catch(err){ res.status(500).json({ Message:err.message }) } })
We can delete a user with the help of a function findByIdAndRemove()
bypassing the id in param.
/** * Update a user with the specified id in the request */ router.put("/:id", async (req, res)=>{ try{ let users= await User.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.status(200).json({ message: "User Updated successfully!", Data: users }) } catch(err){ res.status(500).json({ Message:err.message }) } })
The {new: true}
option in the findByIdAndUpdate()
the method is used to return the modified document to the original.
Congratulations! you're almost done with CRUD Operations in Express, Nodejs, and MongoDB.
const express = require("express") const User = require("../models/users") const router = express.Router() /** * User controller : All business logic goes here */ // Insert router.post("/", async (req, res)=>{ const user= new User({ name: req.body.name email: req.body.email }) try{ let users= await user.save() res.status(200).json({ status: 1, data: users }) } catch(err){ res.status(500).json({ Message:err.message }) } }) /** * Find all Users */ router.get("/", async (req, res)=>{ try{ let users= await User.find(); res.status(200).json(users) } catch(err){ res.status(500).json({ Message:err.message }) } }) /** * Find One Users */ router.get("/:id", async (req, res)=>{ try{ let users= await User.findById(req.params.id); res.status(200).json(users) } catch(err){ res.status(500).json({ Message:err.message }) } /** * Remove One User */ router.delete("/:id", async (req, res)=>{ try{ let users= await User.findByIdAndRemove(req.params.id); res.status(200).json({ message: "User deleted successfully!", Data: users }) } catch(err){ res.status(500).json({ Message:err.message }) } }) /** * Update a user with the specified id in the request */ router.put("/:id", async (req, res)=>{ try{ let users= await User.findByIdAndUpdate(req.params.id, req.body, { new: true }); res.status(200).json({ message: "User Updated successfully!", Data: users }) } catch(err){ res.status(500).json({ Message:err.message }) } module.exports = router
Now the last step left is to set up the routes. go to root file linked index.js, app.js, etc. and put this code see below:
/** * This code rootfile is a linke (index.js, app.js, server.js) */ const express = require('express') const app = express() const port = 3000 const mongoose = require('mongoose') app.get('/', (req, res) => { res.send('Hello World!') }) app.use(express.json()); const userRouter = require("./routes/users") app.use('/user', userRouter) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
Now! You're All done!
Don't forget to test these API's using Postman.
Conclusion
Today we will learn how to create node Js APIs with Mongoose using node js Framework express.
I hope it can help you...
Leave a Reply