Introduction
Node.js has become a popular platform for building scalable and high-performance web applications, due to its event-driven architecture and non-blocking I/O paradigm. MongoDB is a popular NoSQL database, which is known for its flexibility and ease of use. When combined, Node.js and MongoDB provide an ideal stack for building modern web applications. In this tutorial, we will explore how to perform CRUD operations in Node.js using MongoDB, Express, and Mongoose.
Prerequisites
Before we get started, certain prerequisites need to be installed on your system. These include:
Node.js
v19.6.0
NPM (Node Package Manager)
9.4.0
MongoDB
5.0.14
Express
^4.18.2
Mongoose
^7.3.1
Setting up the Project
To get started, we need to create a new project in Node.js. This can be done by running the following command:
$ mkdir crud-node-mongodb
$ cd crud-node-mongodb
$ npm init
This will create a new Node.js project and initialize a package.json file to manage all the dependencies for the project.
Installing the Dependencies
Once the project is created, we need to install the required dependencies, which include:
express
^4.18.2
mongoose
^7.3.1
body-parser
^1.20.2
The following command can be used to install these dependencies:
$ npm install express mongoose body-parser
Connecting to MongoDB
The next step is to connect to our MongoDB database. We can do this by using the Mongoose library. Mongoose provides a simple and elegant API for working with MongoDB. To connect to our database, we need to define a Mongoose connection object in our app.js
file:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/crud-node-mongodb');
Creating a Model
Before we can perform CRUD operations in MongoDB, we need to define a data model. A data model represents the structure and properties of the data that we want to store. In our case, we will define a simple data model to store information about users. Here’s how we can create a user model:
Create a models folder and within that folder create a file called users.js and add the below code to that file
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
email: String,
age: Number
});
const UserModel = mongoose.model('User', UserSchema);
module.exports = UserModel;
Creating Api
Next, we need to create an API for performing CRUD operations. Here’s how we can create the APIs for our CRUD functionality, Create an app.js file at the project root level and add the below code to the app.js file:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/crud-node-mongodb');
const express = require('express');
const Users = require('./models/users');
const bodyParser = require('body-parser');
const app = express();
/* body parser */
app.use(bodyParser.json({ limit: '50mb' }));
/* fetch all users list */
app.get('/', async (req, res) => {
try {
const user = await Users.find() /* find will fetch all users without condition */
return res.status(200).send({ success: true, message: 'Fetched successfully', data: user })
} catch (error) {
return res.status(500).send({ success: false, message: 'Something went wrong', })
}
});
/* create user */
app.post('/add', async (req, res) => {
try {
const user = await Users.create(req.body) /* storing user details in database with help on mongoose */
if (user) return res.status(200).send({ success: true, message: 'Created successfully', data: user })
else return res.status(400).send({ success: false, message: 'Failed', })
} catch (error) {
return res.status(500).send({ success: false, message: 'Something went wrong', })
}
});
/* find the user by id */
app.get('/user/:id', async (req, res) => {
try {
const { id } = req.paramsß
const user = await Users.findById(id) /* findById function used to find the user using _id */
if (user) return res.status(200).send({ success: true, message: 'Fetched successfully', data: user })
else return res.status(400).send({ success: false, message: 'Failed', })
} catch (error) {
return res.status(500).send({ success: false, message: 'Something went wrong', })
}
});
/* update user using id */
app.put('/update/:id', async (req, res) => {
try {
const { id } = req.params /* destructuring */
const user = await Users.findByIdAndUpdate(id, req.body, { new: true }) /* update the user data using the _id */
if (user) return res.status(200).send({ success: true, message: 'Updated successfully', data: user })
else return res.status(400).send({ success: false, message: 'Failed', })
} catch (error) {
return res.status(500).send({ success: false, message: 'Something went wrong', })
}
});
/* delete users using id */
app.delete('/delete/:id', async (req, res) => {
try {
const { id } = req.params
const deleteUser = await Users.findByIdAndRemove(id)
if (deleteUser) return res.status(200).send({ success: true, message: 'Deleted successfully', })
else return res.status(400).send({ success: false, message: 'Failed', })
} catch (error) {
return res.status(500).send({ success: false, message: 'Something went wrong', })
}
});
app.listen(3000, () => console.log('Example app is listening on port 3000.'));
//Add User
// Update user
// Get Users
// Delete User
Conclusion
In this tutorial, we have explored how to perform CRUD operations in Node.js using MongoDB, Express, and Mongoose. We have seen how to connect to a MongoDB database, create a data model, and define routes for performing CRUD operations. With this knowledge, you should now be able to build scalable and high-performance web applications using the Node.js and MongoDB stack.