How to Use MongoDB and Mongoose with Node.js ?
Last Updated :
19 May, 2025
MongoDB is a popular NoSQL database that offers flexibility and scalability, making it an excellent choice for modern applications. Mongoose, a powerful ODM (Object Data Modeling) library, simplifies the interaction between MongoDB and Node.js by providing a schema-based solution for data validation, querying, and model creation. Mongoose streamlines database operations by providing a robust API to interact with MongoDB.
In this article, we will explore how to integrate MongoDB with Mongoose into a Node.js application step by step, providing us with the tools to efficiently manage and interact with our data.
What is Mongoose?
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a straightforward schema-based solution to model our application data. With Mongoose, we can define schemas for our data models, perform validation, create queries, and interact with MongoDB using a more expressive and user-friendly API compared to raw MongoDB commands.
Steps to Integrate MongoDB and Mongoose in Node.js
Follow these steps to create a simple Node.js app that integrates MongoDB and Mongoose.
Step 1: Initialize Your Node.js Project
Ensure that we have Node.js installed on our machine. If not, download and install it from nodejs.org. Create a new directory for our project and initialize it:
mkdir my-node-app
cd my-node-app
npm init -y
Step 2: Install Dependencies
Install Mongoose and Express. Mongoose helps manage MongoDB interactions in a more structured way, while Express is used for setting up the server:
npm install mongoose express
Step 3: Set Up Your Express Server
Create a server.js file and set up a basic Express server. To establish a connection to our MongoDB database using Mongoose:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
dotenv.config();
mongoose.connect(process.env.MONGO_URL)
.then((result) => {
console.log('connected to Mongodb');
}).catch((err) => {
console.error(err);
});
app.listen(8800,()=>{
console.log("backend server is running!!!");
})
Step 4: Establish MongoDB Connection with Mongoose
The connection to MongoDB is handled using Mongoose. Make sure to store the MongoDB URI in a .env
file for security and convenience.
MONGO_URL=mongodb://localhost:27017/mydatabase
In the code above, the mongoose.connect()
method connects your application to MongoDB using the connection string stored in your environment variable MONGO_URL
Step 5: Define a Mongoose Schema and Model
Once connected, we need to define a schema for your data. For example, let's create a schema for a Book
model.
const mongoose = require('mongoose');
const bookSchema = new mongoose.Schema({
title: String,
author: String,
year: Number
});
const Book = mongoose.model('Book', bookSchema);
module.exports = Book;
Step 6: Add Data to the Database Using Mongoose
Now that we have your model defined, we can start adding documents to our MongoDB database.
const mongoose = require('mongoose');
const Book = require('./models/book'); // Path to the Book model
// Connect to MongoDB
mongoose.connect('mongodb+srv://Abdullah:[email protected]/node?retryWrites=true&w=majority');
// Insert books into the database
const books = [
{ title: "The Catcher in the Rye", author: "J.D. Salinger", year: 1951 },
{ title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960 },
{ title: "1984", author: "George Orwell", year: 1949 },
{ title: "The Great Gatsby", author: "F. Scott Fitzgerald", year: 1925 },
{ title: "Pride and Prejudice", author: "Jane Austen", year: 1813 }
];
// Insert multiple documents (books) into the collection
Book.insertMany(books)
.then(() => {
console.log('Books inserted successfully');
mongoose.connection.close(); // Close the connection after insertion
})
.catch((err) => {
console.error('Error inserting books:', err);
mongoose.connection.close(); // Close the connection on error
});
Step 7: Use Postman to Interact with MongoDB Data
To interact with the data in MongoDB, we can create API routes using Express. For instance, to fetch all books from the database, create a simple GET route: Let's create an endpoint to retrieve users from our database and test it using Postman.
1. Create an Express Route
app.get('/books', async (req, res) => {
try {
// Fetch all books from the database
const books = await Book.find();
res.json(books); // Respond with the list of books as JSON
} catch (err) {
console.error('Error fetching books:', err);
res.status(500).json({ message: 'Internal Server Error' });
}
});
2. Testing with Postman
Start your server (node server.js). Open Postman and make a GET request to http://localhost:8800/books.
Hit this URLWe should receive a JSON response with the users stored in our MongoDB database.
Response This URL corresponds to the route we defined in our Express application to fetch all books (/books).
Example
Below is an example to Use MongoDB and Mongoose with Node.js. The code establishes a MongoDB connection using Mongoose, inserts multiple book records, and sets up an API endpoint to fetch all books from the database.
Query:
const express = require('express');
const mongoose = require('mongoose');
const Book = require('./models/book.js');
// Create Express app
const app = express();
// Middleware to parse JSON bodies
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase')
.then(() => {
console.log('Connected to MongoDB');
})
.catch((err) => {
console.error('Error connecting to MongoDB:', err);
});
// Insert books into the database
const books = [
{
title: "The Catcher in the Rye",
author: "J.D. Salinger",
year: 1951
},
{
title: "To Kill a Mockingbird",
author: "Harper Lee",
year: 1960
},
{
title: "1984",
author: "George Orwell",
year: 1949
},
{
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925
},
{
title: "Pride and Prejudice",
author: "Jane Austen",
year: 1813
}
];
// Insert multiple documents (books) into the collection
Book.insertMany(books)
.then(() => {
console.log('Books inserted successfully');
})
.catch((err) => {
console.error('Error inserting books:', err);
});
// Route to fetch all books
app.get('/books', async (req, res) => {
try {
// Fetch all books from the database
const books = await Book.find();
res.json(books); // Respond with the list of books as JSON
} catch (err) {
console.error('Error fetching books:', err);
res.status(500).json({ message: 'Internal Server Error' });
}
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Output
Use MongoDB and Mongoose with Node.jsExplanation:
- The console will display a message indicating that the connection to MongoDB was successful. After inserting the books, another message will appear confirming the successful insertion of the books.
- When the
/books
route is accessed, the API will return a JSON array of all the books in the database, showcasing their title
, author
, and year
fields. If there’s an issue with the query or the database connection, an error message will be logged in the console.
Conclusion
In this article, we've covered the basics of integrating MongoDB and Mongoose with Node.js. We learned how to establish a connection to MongoDB using Mongoose, define schemas and models, add data to the database, and create endpoints to interact with our data using Express and Postman. This setup forms a solid foundation for building robust and scalable Node.js applications backed by MongoDB. Explore further by implementing more complex schemas, relationships between models, and advanced queries with Mongoose.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read