Open In App

Connect MongoDB with Node App using MongooseJS

Last Updated : 21 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The process of integrating MongoDB, a NoSQL database, with a Node.js application using MongooseJS, a MongoDB object modelling tool designed to work in an asynchronous environment.

Prerequisites:

Steps to connect MongoDB with Node App

Following are the steps to connect MongoDB with a Node.js application using MongooseJS:

Step 1. Install MongoDB

First, you need to install MongoDB on your system or use a cloud-based MongoDB service like MongoDB Atlas.

Step 2. Create a Node.js Application

Set up a Node.js application by initializing a new project with npm (Node Package Manager) and installing necessary dependencies.

npm init -y

Step 3. Install MongooseJS

Use npm to install MongooseJS in your Node.js project. MongooseJS allows you to interact with MongoDB from Node.js using an easy-to-use API.

npm install mongoose

Folder Structure:

FolderStructure

Folder Strucutre

Updated Dependencies:

Dependencies

Updated Dependencies

Step 4. Connect to MongoDB

In your Node.js application, establish a connection to your MongoDB database using MongooseJS. This typically involves specifying the MongoDB connection URI and handling connection events.

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

// Handle connection events
const db = mongoose.connection;
db
    .on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
    console.log('Connected to MongoDB');
});

Replace ‘mongodb://localhost:27017/mydatabase’ with the appropriate MongoDB connection URI for your environment.

Step 5. Define Mongoose Schema

Define Mongoose schema to specify the structure of your MongoDB documents. This includes defining fields, types, validations, and other options.

const { Schema } = mongoose;

const userSchema = new Schema({
    name: String,
    email: { type: String, required: true, unique: true },
    age: Number
});

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

Step 6. Perform CRUD Operations

With MongooseJS, you can easily perform CRUD (Create, Read, Update, Delete) operations on your MongoDB database using Mongoose models.

// Create a new user
const newUser = new User({ name: 'John', email: 'john@example.com', age: 30 });
newUser.save()
    .then(() => console.log('User created'))
    .catch(err => console.error(err));

// Find users
User.find({ age: { $gte: 25 } })
    .then(users => console.log('Users:', users))
    .catch(err => console.error(err));

// Update a user
User.updateOne({ _id: 'user_id' }, { age: 35 })
    .then(() => console.log('User updated'))
    .catch(err => console.error(err));

// Delete a user
User.deleteOne({ _id: 'user_id' })
    .then(() => console.log('User deleted'))
    .catch(err => console.error(err));

Step 7. Close MongoDB Connection

Close the MongoDB connection when your Node.js application terminates or shuts down gracefully.

// Close MongoDB connection
mongoose.connection.close(() => {
    console.log('Disconnected from MongoDB');
});

By following these steps, you can seamlessly connect MongoDB with your Node.js application using MongooseJS, allowing you to store and retrieve data from MongoDB in a structured and efficient manner.

Example: To demonstrate connecting MongoDB with the Node app using the MongooseJS.

// index.js file
const mongoose = require('mongoose');

// Connect to MongoDB
mongoose.connect('database URI', {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
    console.log('Connected to MongoDB');

    // Define Mongoose schema
    const userSchema = new mongoose.Schema({
        name: String,
        email: { type: String, required: true, unique: true },
        age: Number
    });

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

    // Perform CRUD operations

    // Create a new user
    const newUser = new User({ name: 'John', email: 'john@example.com', age: 30 });
    newUser.save()
        .then(() => {
            console.log('User created');

            // Find users with age >= 25
            return User.find({ age: { $gte: 25 } });
        })
        .then(users => {
            console.log('Users:', users);

            // Assuming you have a valid ObjectId for the user you want to update
            const userIdToUpdate = '6123456789abcdef01234567'; // Replace with actual ObjectId
            return User.updateOne({ _id: userIdToUpdate }, { age: 35 });
        })
        .then(() => {
            console.log('User updated');

            // Assuming you have a valid ObjectId for the user you want to delete
            const userIdToDelete = '6123456789abcdef01234567'; // Replace with actual ObjectId
            return User.deleteOne({ _id: userIdToDelete });
        })
        .then(() => {
            console.log('User deleted');

            // Close MongoDB connection
            mongoose.connection.close();
        })
        .catch(err => console.error(err));
});

Output:

MongoDB-connection

MongoDB connection



Next Article

Similar Reads

three90RightbarBannerImg