![]() |
VOOZH | about |
Node.js, Mongoose, and MongoDB Atlas work together to simplify modern database operations through structured data modeling and cloud-based storage. This combination enables developers to efficiently perform CRUD operations while ensuring scalability and security.
Here are the steps to setting up Node.js CRUD with Mongoose & MongoDB:
Start by creating a new Node.js project. If you haven’t done so already, we can initialize your project by running the following commands:
mkdir nodejs-crud
cd nodejs-crud
npm init -y
This command initializes a package.json file in your project folder. The -y flag auto-generates the package.json file with default values.
The next step is to set up a basic folder structure for the project:
mkdir src
cd src
This folder will contain your application logic, such as the server, routes, models, etc.
Express is a minimal web framework for Node.js that makes building APIs easy. Mongoose simplifies the interaction between Node.js and MongoDB by allowing you to define models, Schemas, and interact with the database.
Install both dependencies by running:
npm install express mongoose --saveOnce installed, we’re ready to build the basic structure of our server.
MongoDB Atlas is a cloud database that takes the hassle out of hosting your MongoDB instance. It’s scalable, secure, and easy to set up. Follow these steps to set up a MongoDB Atlas cluster:
The connection string will look like this:
mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majorityReplace <username> and <password> with the credentials you created.
Postman allows us to send HTTP requests to your Node.js API endpoints and check if everything is working. Here’s how to set it up for testing:
Here, we'll set up our server on port 3000 and call the express function that returns a server object in a variable named app. Then we start the listener saying app. Listen with the port address. Finally, we create the /api route which will be triggered once the request localhost:3000/api is received from the browser.
Example: This example demonstrates setting up basic express app.
Output:
Schema is a representation of the structure of the data. It allows us to decide exactly what data we want, and what options we want the data to have as an object. In this example, we’ll create a schema for a Student collection. Create a new file called studentschema.js in the src folder and define the schema:
Example: This example creates mongoose schema for Student having student id, name, roll no, birthday and address.
When a request is made to localhost:3000/api, Express searches for the api route and executes the api.js file.
The database is College and the collection inside the database in Students.
1. Create (POST): Create a new student object using the StudentModel and save it to the database using .save().
We can even insert new documents without hardcoding the fields as done above. For that, we need to change the request from GET to POST and use the body-parser middleware to accept the new student's data. This ensures that we can insert details of as many students as we need.
router.post('/save', function (req, res) {
const newStudent = new StudentModel();
newStudent.StudentId = req.body.StudentId;
newStudent.Name = req.body.Name;
newStudent.Roll = req.body.Roll;
newStudent.Birthday = req.body.Birthday;
newStudent.save(function (err, data) {
if (err) {
console.log(error);
}
else {
res.send("Data inserted");
}
});
});
2. Read (GET): To retrieve records from a database collection we make use of the .find() function.
router.get('/findall', function (req, res) {
StudentModel.find(function (err, data) {
if (err) {
console.log(err);
}
else {
res.send(data);
}
});
});
To retrieve a single record or the first matched document we make use of the function findOne().
router.get('/findfirst', function (req, res) {
StudentModel.findOne({ StudentId: { $gt: 185 } },
function (err, data) {
if (err) {
console.log(err);
}
else {
res.send(data);
}
});
});
3. Delete (DELETE): To delete a record from the database, we make use of the function .remove(). It accepts a condition that is the parameter according to which it performs deletion. Here the condition is Id:188.
router.get('/delete', function (req, res) {
StudentModel.remove({ StudentId: 188 },
function (err, data) {
if (err) {
console.log(err);
}
else {
res.send(data);
}
});
});
We can also use the .findByIdAndDelete() method to easily remove a record from the database. Every object created with Mongoose is given its own _id, and we can use this to target specific items with a DELETE request.
router.post('/delete', function (req, res) {
StudentModel.findByIdAndDelete((req.body.id),
function (err, data) {
if (err) {
console.log(err);
}
else {
res.send(data);
console.log("Data Deleted!");
}
});
});
4. Update (PUT): Just like with the delete request, we’ll be using the _id to target the correct item. .findByIdAndUpdate() takes the target’s id, and the request data you want to replace it with.
router.post('/update', function (req, res) {
StudentModel.findByIdAndUpdate(req.body.id,
{ Name: req.body.Name }, function (err, data) {
if (err) {
console.log(err);
}
else {
res.send(data);
console.log("Data updated!");
}
});
});