Open In App

How to Connect MongoDB with a Node.js Application using MongooseJS

Last Updated : 09 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Mongoose is a powerful MongoDB object modeling library for Node.js enabling you to easily interact between your Node.js app and MongoDB. In this article we are going to explore how you can connect your Node.js app to MongoDB using MongooseJS. You will learn how to create a connection, specify schemas, and perform CRUD operations with MongoDB efficiently.

What is MongooseJS?

MongooseJS is an Object Data Modeling library for Node.js and MongoDB. It provides a lightweight API for accessing MongoDB databases, data modeling based on schema, and powerful query building and validation. Mongoose simplifies working with MongoDB in an asynchronous environment and makes defining and manipulating documents easy.

Steps to connect MongoDB with Node App

Below are the steps to establish MongoDB with a Node.js application through MongooseJS:

Step 1. Install MongoDB

Install MongoDB on your local system or take advantage of a cloud MongoDB service such as MongoDB Atlas to host your databases with ease. For local setups, refer to the official MongoDB documentation.

Step 2. Create a Node.js Application

Initialize a new Node.js application by running a new project using npm (Node Package Manager) and creating relevant dependencies.

mkdir my-node-app
cd my-node-app
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');
});

Make sure to replace 'mongodb://localhost:27017/mydatabase' with your actual MongoDB URI if using a cloud database like MongoDB Atlas.

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: '[email protected]', 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 doing so, you will be able to integrate MongoDB with your Node.js application using MongooseJS such that you are able to write and read data in MongoDB in an efficient and structured way.

Example: Full Node.js Application Connecting to MongoDB

Here’s a full example of connecting MongoDB with a Node.js app using Mongoose and performing basic CRUD operations:

// 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: '[email protected]', 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

Explanation: The application will display the process of creating, reading, updating, and deleting user documents. Once the CRUD operations are done, the app closes the MongoDB connection.

Conclusion

Through the above steps, you can successfully integrate MongoDB with your Node.js application using Mongoose. This strong integration allows you to deal with your MongoDB database in an easy and systematic manner. With in-built features of Mongoose like validation, schema definition, and CRUD operations, developing robust and scalable MongoDB-based applications is convenient.


Next Article

Similar Reads