Saturday, 15 March 2025

MongoDB Integration with Express: A Step-by-Step Guide to CRUD Operations Using Mongoose

MongoDB is a powerful NoSQL database, and integrating it with an Express.js application is made easy with Mongoose. In this guide, we'll go through the step-by-step process of setting up MongoDB, installing Mongoose, defining a schema, and performing CRUD operations.





1. Install MongoDB Compass

MongoDB Compass is a graphical user interface (GUI) for managing MongoDB databases. You can download and install it from the official website:

🔗 Download MongoDB Compass

Once installed, you can use it to visualize and manage your database.




2. Install Mongoose

Mongoose is an Object Data Modeling (ODM) library for MongoDB, making it easier to interact with the database. To install it, run the following command in your project directory:

npm i mongoose



3. Define the Database and Collection in Mongoose

Now, create a new file named user.js in your project directory. This file will define the database connection and schema.

const mongoose = require("mongoose");

// Connect to MongoDB (Make sure MongoDB is running locally)
mongoose.connect("mongodb://127.0.0.1:27017/data1", {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

// Define schema for the collection
const userSchema = mongoose.Schema({
    username: String,
    name: String,
    age: Number
});

// Export the model
module.exports = mongoose.model("student", userSchema);

4. Perform CRUD Operations in Express.js

Now, let's integrate MongoDB operations in the index.js file using Express.

a. Create a User (Insert Data)

This route creates a new user in the database.

const express = require('express');
const router = express.Router();
const userModel = require('./user'); // Import the user model

router.get('/', async function(req, res) {
    const user = await userModel.create({
        username: "Asma",
        age: 33,
        name: "Asma"
    });

    res.send(user);
});

b. Find a User (Retrieve Data)

This route fetches a user with a specific name.

router.get('/userone', async function(req, res) {
    let user = await userModel.findOne({ name: "mahine" });
    res.send(user);
});

c. Delete a User

This route deletes a user with a specific name.

router.get('/delete', async function(req, res) {
    let deletedUser = await userModel.findOneAndDelete({ name: "mahine" });
    res.send(deletedUser);
});

5. Checking the Database Updates

After adding, retrieving, or deleting users, you can check your MongoDB Compass to see the changes reflected in the data1 database under the students collection.


6. Running the Application

To run the application, first, install nodemon if you haven't already:

npm i -g nodemon

Now, start the server:

npx nodemon index.js

7. Testing the CRUD Operations

Open your browser or use Postman to test the following endpoints:

  1. Create a user:
    http://localhost:3000/
    
  2. Find a user:
    http://localhost:3000/userone
    
  3. Delete a user:
    http://localhost:3000/delete
    


No comments:

Post a Comment