Building a CRUD Application with Node.js, MongoDB, and Mongoose

Introduction
In this tutorial, we will learn how to create a CRUD (Create, Read, Update, Delete) application using Node.js, MongoDB, and Mongoose. We will go through each step of the process, using code snippets for explanation.So, let's get started and build our own CRUD application!
Tech Stack
We will be using the following technologies in this tutorial:
Node.js: A JavaScript runtime that allows us to run JavaScript code outside of a web browser. It provides an efficient way to build server-side applications.
MongoDB: A popular NoSQL database that stores data in a flexible JSON-like format called BSON. It offers scalability, high performance, and schema flexibility, making it ideal for modern web applications.
Mongoose: An Object Data Modeling (ODM) library for Node.js and MongoDB. It simplifies interacting with MongoDB by providing schema and model definitions, as well as validation and query building capabilities.
Let's Build
Step 1: Setting up the Environment
To begin, make sure you have Node.js and MongoDB installed on your machine. Create a new directory for your project and navigate to it using the command line. Initialize a new Node.js project by running the command: npm init. Follow the prompts and enter the necessary details to generate a package.json file.
Step 2: Installing Dependencies
Next, install the required dependencies: Express, MongoDB, and Mongoose. Run the command npm install express mongodb mongoose in your project directory.
Step 3: Creating the Express Server
Create a new file called server.js in your project directory and open it in your code editor. Add the following code snippet to create an Express server:
const express = require('express');
const app = express();
const port = 3100;
app.use(express.json());
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Step 4: Connecting to MongoDB
Establish a connection to your MongoDB database by adding the following code snippet after the app.listen line:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/crud-app', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
}).catch((error) => {
console.error('Error connecting to MongoDB:', error);
});
Ensure that you replace 'mongodb://localhost/crud-app' with the appropriate URL for your MongoDB database.
Step 5: Defining the Data Schema
Define a Mongoose schema for your data by adding the following code snippet below the MongoDB connection code:
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
email: String,
age: Number
});
const User = mongoose.model('User', userSchema);
Implementing the CRUD Operations
Implement the CRUD operations for your application by adding the following code snippets below the data schema code:
a) Create Operation:
app.post('/users', (req, res) => {
const newUser = new User(req.body);
newUser.save().then(() => {
res.status(201).json({ message: 'User created successfully' });
}).catch((error) => {
res.status(400).json({ error: 'Error creating user' });
});
});
Here, we define a route to handle the HTTP POST request for creating a new user. We create a new instance of the User model with the data from the request body, save it to the database using the save method, and return a success or error response.
Here is the screenshot of the response which you can expect:
b) Read Operation:
app.get('/users', (req, res) => {
User.find().then((users) => {
res.json(users);
}).catch((error) => {
res.status(500).json({ error: 'Error retrieving users' });
});
});
Here, We define a route to handle the HTTP GET request for retrieving all users. We use the find method on the User model to retrieve all user documents from the database and return them as a response.
Here is the screenshot of the response which you can expect:
If you want to retrieve data in batches then below code helps you to get paginated data.
app.get('/users?start=10&limit=10', (req, res) => {
let skip = req.query.start || 0;
let limit = req.query.limit || 10;
User.find()
.skip(skip)
.limit(limit)
.then((users) =>
{
res.json(users);
})
.catch((error) => {
res.status(500).json({ error: 'Error retrieving users' });
});
});
c) Update Operation:
app.put('/users/:id', (req, res) => {
User.findByIdAndUpdate(req.params.id, req.body).then(() => {
res.json({ message: 'User updated successfully' });
}).catch((error) => {
res.status(400).json({ error: 'Error updating user' });
});
});
Here, we define a route to handle the HTTP PUT request for updating a user. We use the findByIdAndUpdate method on the User model to find and update a user document based on the provided ID and request body.
Here is the screenshot of the response which you can expect:
d) Delete Operation:
app.delete('/users/:id', (req, res) => {
User.findByIdAndDelete(req.params.id).then(() => {
res.json({ message: 'User deleted successfully' });
}).catch((error) => {
res.status(400).json({ error: 'Error deleting user' });
});
});
Here, we define a route to handle the HTTP DELETE request for deleting a user. We use the findByIdAndDelete method on the User model to find and delete a user document based on the provided ID.
Here is the screenshot of the response which you can expect:
Source code available in Github
Conclusion
Congratulations! You have successfully built a CRUD application using Node.js, MongoDB, and Mongoose. We covered the entire process, from setting up the environment to implementing the CRUD operations. You now have a foundation to build upon and create more complex applications using these technologies. Remember to continue exploring and experimenting to enhance your understanding.
Happy coding!