Open In App

Node.js CRUD Operations Using Mongoose and MongoDB Atlas

Last Updated : 29 Sep, 2025
Comments
Improve
Suggest changes
16 Likes
Like
Report

Node.js, Mongoose, and MongoDB Atlas simplify database operations by enabling schema-based data modeling and cloud storage. With Mongoose, performing Create, Read, Update, and Delete (CRUD) operations becomes easy, structured, and efficient, while MongoDB Atlas provides secure, scalable cloud hosting.

Node.js CRUD with Mongoose

Here are the steps to setting up Node.js CRUD with Mongoose & MongoDB:

Step 1: Initialize Node project

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.

Step 2: Install Mongoose and Express

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 --save
  • Express: A fast and minimal web framework for Node.js.
  • Mongoose: An ODM (Object Data Modeling) library that works as an abstraction layer between your Node.js code and MongoDB.

Once installed, we’re ready to build the basic structure of our server.

Step 3: Setting Up MongoDB Atlas

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:

  1. Sign Up and Log In: Create an account on MongoDB Atlas.
  2. Create a Cluster: From the MongoDB Atlas dashboard, create a free-tier cluster. It will use the shared cluster for small-scale testing and development purposes.
  3. Create a Database User: Once your cluster is created, go to the "Database Access" section and add a new database user. Provide a username and password (make sure to store these securely).
  4. Whitelist Your IP Address: Go to the “Network Access” section and add your current IP address to the whitelist, so your server can connect to the database.
  5. Get the Connection URI: Once everything is set up, go to the "Clusters" section, click “Connect,” and copy the connection string.

The connection string will look like this:

mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority

Replace <username> and <password> with the credentials you created.

Step 4: Configuring Postman for API Testing

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:

  1. Create a New Collection: Group your API requests in collections to keep things organized.
  2. Create Requests for Each CRUD Operation: Set up requests for each of the CRUD operations we will implement (POST, GET, PUT, DELETE).
  3. Test Your Endpoints: Use the relevant HTTP method (GET, POST, PUT, DELETE) to send requests to your server. Ensure that you can add, retrieve, update, and delete data from your MongoDB Atlas database.

Step 5: Creating the Server with Express

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.

server.js
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const api = require('./api');

const port = 3000;
const app = express();

app.listen(port, function () {
    console.log("Server is listening at port:" + port);
});

// Parses the text as url encoded data
app.use(bodyParser.urlencoded({ extended: true }));

// Parses the text as json
app.use(bodyParser.json());

app.use('/api', api);

Output:

crud node js, mongodb
Server running on desired port
crud node js, mongodb
Sample output to check working of api route

Step 6: Defining Mongoose Schema for CRUD Operations

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.

studentschema.js
// studentschema.js
const mongoose = require('mongoose');

const StudentSchema = new mongoose.Schema({
    StudentId: Number,
    Name: String,
    Roll: Number,
    Birthday: Date,
    Address: String
});

module.exports = mongoose.model(
    'student', StudentSchema, 'Students');

In this example:

  • Create a schema named StudentSchema with fields: Id, Name, Roll, Birthday, and Address.
  • Models provide predefined methods to insert, update, delete, and retrieve data from the database.
  • Use mongoose.model to link the schema with a collection and make it usable with actual data.
  • Export the model so it can be used in api.js

Advanced Routing and MongoDB Connections

When a request is made to localhost:3000/api, Express searches for the api route and executes the api.js file.

app.js
const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();
const StudentModel = require('./studentschema');

// Connecting to database
const query = 'mongodb+srv://Username:<password>'
    + '@student.tuufn.mongodb.net/College?'
    + 'retryWrites=true&w=majority'

const db = (query);
mongoose.Promise = global.Promise;

mongoose.connect(db, {
    useNewUrlParser: true,
    useUnifiedTopology: true
}, function (error) {
    if (error) {
        console.log("Error!" + error);
    }
});

module.exports = router;


The database is College and the collection inside the database in Students.

crud node js, mongodb
A Glimpse of the Mongo Database

Step 7: Implementing CRUD Operations 

1. Create (POST): Create a new student object using the StudentModel and save it to the database using .save().

JavaScript
router.get('/save', function (req, res) {
    const newStudent = new StudentModel({
        StudentId: 101, 
        Name: "Sam", Roll: 1, Birthday: 2001 - 09 - 08
    });

    newStudent.save(function (err, data) {
        if (err) {
            console.log(error);
        }
        else {
            res.send("Data inserted");
        }
    });
});

In this example:

  • Create a new student instance using StudentModel.
  • Store it in a variable called newStudent.
  • Use newStudent.save() to insert the student into the database.
  • Test it in Postman with a GET request to localhost:3000/api/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);
        }
    });
});

In this example:

  • Open Postman.
  • Make a new GET request to localhost:3000/api/findall.
  • Click Send.
  • All student documents from the database collection are returned.

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);
            }
        });
});

In this example:

  • Open Postman.
  • Send a GET request to localhost:3000/api/findfirst.
  • Click Send.
  • It returns the first student record where StudentId > 185 ($gt means greater than).

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!");
            }
        });
});

Article Tags :

Explore