Nodejs Crud Operations Mongodb Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    7 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of NodeJS CRUD Operations MongoDB


Node.js CRUD Operations with MongoDB

Node.js is a powerful runtime that allows you to build scalable network applications, and MongoDB is a popular NoSQL database known for its flexibility and scalability. Integrating Node.js with MongoDB using the official MongoDB driver or ODMs like Mongoose allows developers to perform CRUD operations efficiently.

1. Setting Up

Before writing CRUD operations, ensure:

  • Node.js is installed.
  • MongoDB is installed and running.
  • The mongodb package or mongoose ODM is installed in your Node.js project.

Install MongoDB Node.js Driver:

npm install mongodb

Install Mongoose ODM:

npm install mongoose

2. Connecting to MongoDB

Using MongoDB Driver: First, establish a connection to MongoDB.

const { MongoClient } = require('mongodb');

async function main() {
  const uri = "mongodb://localhost:27017"; // Connection String
  const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

  try {
    await client.connect();
    console.log("Connected successfully to MongoDB.");
  } finally {
    await client.close();
  }
}

main().catch(console.error);

Using Mongoose:

const mongoose = require('mongoose');

async function main() {
  const uri = "mongodb://localhost:27017"; // Connection String

  await mongoose.connect(uri, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  });

  console.log("Connected successfully to MongoDB.");
}

main().catch(err => console.error(err));

3. Creating a Collection & Schema (Mongoose Only)

Define Mongoose Schema:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: String,
  age: Number,
  email: String
});

const User = mongoose.model('User', userSchema);

4. CRUD Operations

Create (Insert) Documents:

Using MongoDB Driver:

async function createDoc(client, newDoc) {
  const result = await client.db("sample_db").collection("users").insertOne(newDoc);
  console.log(`New document created with the following id: ${result.insertedId}`);
}

// Example Document
const newUser = { name: "John Doe", age: 30, email: "john.doe@example.com" };
createDoc(client, newUser).then().catch(console.error);

Using Mongoose:

async function createDoc(userDoc) {
  const user = new User(userDoc);
  await user.save();
  console.log(`New document created with the following id: ${user._id}`);
}

// Example Document
const newUser = { name: "Jane Doe", age: 25, email: "jane.doe@example.com" };
createDoc(newUser).then().catch(console.error);

Read (Find) Documents:

Using MongoDB Driver:

async function findDocs(client, query) {
  const cursor = client.db("sample_db").collection("users").find(query);
  const results = await cursor.toArray();
  if (results.length > 0) {
    console.log(`Found documents =>`);
    results.forEach((doc, index) => console.log(`${index + 1}. ${doc}`));
  } else {
    console.log(`No documents found with the query ${query}`);
  }
}

// Example Query
const query = { age: { $gt: 20 } };
findDocs(client, query).then().catch(console.error);

Using Mongoose:

async function findDocs(query) {
  const foundDocs = await User.find(query);
  if (foundDocs.length > 0) {
    console.log(`Found documents =>`);
    foundDocs.forEach((doc, index) => console.log(`${index + 1}. ${doc}`));
  } else {
    console.log(`No documents found with the query ${query}`);
  }
}

// Example Query
const query = { age: { $gt: 20 } };
findDocs(query).then().catch(console.error);

Update Documents:

Using MongoDB Driver:

async function updateDoc(client, filter, updateDoc) {
  const result = await client.db("sample_db").collection("users").updateOne(filter, { $set: updateDoc });
  console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`);
}

// Example Filter & Update
const filter = { name: "John Doe" };
const updateDoc = { age: 31 };
updateDoc(client, filter, updateDoc).then().catch(console.error);

Using Mongoose:

async function updateDoc(filter, updateDoc) {
  const result = await User.updateOne(filter, { $set: updateDoc });
  console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`);
}

// Example Filter & Update
const filter = { email: "jane.doe@example.com" };
const updateDoc = { age: 26 };
updateDoc(filter, updateDoc).then().catch(console.error);

Delete Documents:

Using MongoDB Driver:

async function deleteDoc(client, query) {
  const result = await client.db("sample_db").collection("users").deleteOne(query);
  console.log(`${result.deletedCount} document(s) was/were deleted.`);
}

// Example Query
const query = { name: "John Doe" };
deleteDoc(client, query).then().catch(console.error);

Using Mongoose:

async function deleteDoc(query) {
  const result = await User.deleteOne(query);
  console.log(`${result.deletedCount} document(s) was/were deleted.`);
}

// Example Query
const query = { email: "jane.doe@example.com" };
deleteDoc(query).then().catch(console.error);

5. Summary

This guide covered setting up MongoDB with Node.js, creating a basic schema using Mongoose, and performing CRUD operations using both the MongoDB driver and Mongoose ODM. Using these tools effectively can help you build scalable applications that interact with MongoDB seamlessly.



Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement NodeJS CRUD Operations MongoDB

Prerequisites

Before we begin, ensure you have the following installed:

  1. Node.js: Download and install from https://nodejs.org/.
  2. MongoDB: Download and install from https://www.mongodb.com/try/download/community. Or, you can use a cloud service like MongoDB Atlas.
  3. npm (Node Package Manager): This usually comes with Node.js.
  4. Postman: Download and install from https://www.postman.com/ for testing our API endpoints.

Step 1: Set Up Your Project

Create a new directory for your project and initialize a new Node.js project.

mkdir nodejs-crud-api
cd nodejs-crud-api
npm init -y

Step 2: Install Required Packages

Install Express.js (for handling HTTP requests) and Mongoose (a popular ODM for MongoDB):

npm install express mongoose

Step 3: Create the Basic Server

Create a file named server.js and set up a basic Express server.

// server.js
const express = require('express');
const mongoose = require('mongoose');

// Initialize app
const app = express();

// Middleware to parse JSON
app.use(express.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// Check connection
mongoose.connection.once('open', () => {
  console.log('Connected to MongoDB');
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Step 4: Define Your Mongoose Model

Define a model for the data you want to store in MongoDB.

Create a new file named models/Item.js:

// models/Item.js
const mongoose = require('mongoose');

const itemSchema = new mongoose.Schema({
  name: { type: String, required: true },
  quantity: { type: Number, required: true },
  price: { type: Number, required: true },
});

module.exports = mongoose.model('Item', itemSchema);

Step 5: Create CRUD Routes

Add routes to handle CRUD operations.

Modify server.js to include routes:

// server.js
const express = require('express');
const mongoose = require('mongoose');
const Item = require('./models/Item');

const app = express();
app.use(express.json());

mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

mongoose.connection.once('open', () => {
  console.log('Connected to MongoDB');
});

// Create a new item
app.post('/items', async (req, res) => {
  try {
    const item = new Item(req.body);
    await item.save();
    res.status(201).send(item);
  } catch (error) {
    res.status(400).send(error);
  }
});

// Get all items
app.get('/items', async (req, res) => {
  try {
    const items = await Item.find();
    res.status(200).send(items);
  } catch (error) {
    res.status(500).send(error);
  }
});

// Get an item by ID
app.get('/items/:id', async (req, res) => {
  try {
    const item = await Item.findById(req.params.id);
    if (!item) {
      return res.status(404).send();
    }
    res.status(200).send(item);
  } catch (error) {
    res.status(500).send(error);
  }
});

// Update an item by ID
app.put('/items/:id', async (req, res) => {
  try {
    const item = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
    if (!item) {
      return res.status(404).send();
    }
    res.status(200).send(item);
  } catch (error) {
    res.status(400).send(error);
  }
});

// Delete an item by ID
app.delete('/items/:id', async (req, res) => {
  try {
    const item = await Item.findByIdAndDelete(req.params.id);
    if (!item) {
      return res.status(404).send();
    }
    res.status(200).send(item);
  } catch (error) {
    res.status(500).send(error);
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Step 6: Test Your API

  1. Start your server:

    node server.js
    
  2. Use Postman to test your API endpoints:

    • Create an item:

      • Endpoint: POST http://localhost:3000/items

      • Body (JSON):

        {
          "name": "Apple",
          "quantity": 10,
          "price": 0.99
        }
        
    • Get all items:

      • Endpoint: GET http://localhost:3000/items
    • Get an item by ID:

      • Endpoint: GET http://localhost:3000/items/<item_id>
    • Update an item by ID:

      • Endpoint: PUT http://localhost:3000/items/<item_id>

      • Body (JSON):

        {
          "quantity": 15
        }
        
    • Delete an item by ID:

      • Endpoint: DELETE http://localhost:3000/items/<item_id>

Summary

In this tutorial, we covered setting up a basic Node.js application that interacts with a MongoDB database using Mongoose. We defined a model for our data and created routes to handle CRUD operations. Using Postman, we tested these endpoints to ensure they worked as expected.

Top 10 Interview Questions & Answers on NodeJS CRUD Operations MongoDB

1. What is Node.js and MongoDB used for in web development?

Answer: Node.js is a runtime environment for building scalable and high-performance server-side applications using JavaScript. It's lightweight and efficient, thanks to its event-driven architecture. MongoDB, on the other hand, is a NoSQL database that stores data in flexible, JSON-like documents. It’s renowned for its scalability, flexibility, and ease of use. Together, Node.js and MongoDB make an excellent combination for developing modern web applications where data structure might evolve over time or where you need to handle large volumes of data efficiently.

2. How can I install Node.js and MongoDB on my system?

Answer: To install Node.js, visit nodejs.org and download the installer suitable for your operating system. The installer includes npm (Node Package Manager), which you’ll use to install Node.js packages.

For MongoDB, you have several options:

  • Docker: Pull the MongoDB image with docker pull mongo and run it using docker-compose up -d or docker run -d --name my-mongo-mongo -p 27017:27017 mongo.
  • MongoDB Community Server: Download and follow the installation instructions provided on the official website.
  • Cloud Services: Use a cloud service like MongoDB Atlas for a managed database service.

3. What is Mongoose, and why is it used in Node.js with MongoDB?

Answer: Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides schema validation, middleware support, query building, business logic hooks, and more. Mongoose simplifies working with MongoDB by allowing you to define schemas for your data and interacting with MongoDB through objects and methods rather than writing raw queries.

4. How do I set up a basic Node.js application with MongoDB?

Answer: Here’s a simple example:

  1. Initialize a Node.js Project:

    mkdir node-mongo-crud
    cd node-mongo-crud
    npm init -y
    
  2. Install Required Packages:

    npm install express mongoose
    
  3. Create a Basic Express Application (app.js):

    const express = require('express');
    const mongoose = require('mongoose');
    const app = express();
    app.use(express.json());
    
    mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
        .then(() => console.log('MongoDB connected'))
        .catch(err => console.log(err));
    
    app.listen(3000, () => console.log('Server started on port 3000'));
    

5. How do I create a new document in MongoDB using Node.js?

Answer: Assume you have defined a schema and model. Here’s how to create a new document:

const UserSchema = new mongoose.Schema({
    name: String,
    email: String,
});

const User = mongoose.model('User', UserSchema);

function createUser(name, email) {
    const newUser = new User({ name, email });
    newUser.save()
        .then(user => console.log('User created:', user))
        .catch(err => console.error('Error creating user:', err));
}

6. How do I read documents from MongoDB using Node.js?

Answer: You can use queries like .find(), .findById(), or .findOne() to retrieve documents.

// Retrieve all users
User.find({}, (err, users) => {
    if (err) return console.error("Error fetching users", err);
    console.log(users); // Array of users
});

// Retrieve a single user by ID
User.findById(userId, (err, user) => {
    if (err) return console.error("Error fetching user", err);
    console.log(user); // Single user object
});

7. How do I update documents in MongoDB using Node.js?

Answer: The .updateOne() method is commonly used for updating single documents:

// Update a user by their ID
User.updateOne({ _id: userId }, { $set: { name: 'New Name' } }, (err, result) => {
    if (err) return console.error("Error updating user", err);
    console.log(result); // Result of the update
});

Alternatively, use a more modern method like findOneAndUpdate():

User.findOneAndUpdate({ _id: userId }, { $set: { name: 'New Name' } }, { new: true }) // new: true returns the updated document
    .then(updatedUser => console.log("Updated:", updatedUser))
    .catch(err => console.error("Error updating user", err));

8. How can I delete documents in MongoDB with Node.js?

Answer: The .deleteOne() or .remove() methods can be used for deleting. Prefer the newer deleteOne() or deleteMany():

// Delete a user by their ID
User.deleteOne({ _id: userId }, (err) => {
    if (err) return console.error("Error deleting user", err);
    console.log("User deleted successfully");
});

// Another example using findByIdAndDelete
User.findByIdAndDelete(userId)
    .then(() => console.log("User deleted"))
    .catch(err => console.error("Error deleting user", err));

9. What is aggregation pipeline in MongoDB, and how can I implement it in a Node.js application?

Answer: MongoDB's Aggregation Pipeline is a powerful tool for processing and transforming documents. It allows you to aggregate multiple documents and can perform various stages like $match, $group, $sort, and more.

Example in Node.js:

User.aggregate([
    { $match: { age: { $gt: 25 } } }, // Stage 1: Filter users older than 25
    { $group: { _id: "$status", total: { $sum: 1 } } }, // Stage 2: Group by status & count
]).then(result => console.log(result))
.catch(err => console.error(err));

10. How do I handle errors when performing CRUD operations in MongoDB with Node.js?

Answer: Error handling is crucial when performing CRUD operations to ensure your application runs smoothly and provides useful feedback. Use try-catch blocks along with Promises for better error management.

Example for Create operation:

You May Like This Related .NET Topic

Login to post a comment.