Mon Jul 31 2023
How to Connect Node.js with MongoDB using Mongoose
Connecting Node.js applications to MongoDB is a common task for developers building dynamic web applications. MongoDB is a popular NoSQL database that stores data in a flexible, JSON-like format. To interact with MongoDB efficiently, developers often use Mongoose, an ODM (Object Data Modeling) library for MongoDB and Node.js. Mongoose provides a straightforward and schema-based solution for managing MongoDB collections. In this article, we will go through the steps to set up a connection between Node.js and MongoDB using Mongoose, and provide a sample code to demonstrate how to interact with the database.
Step 1: Add Mongoose Library on Your Node.js Project
Install Mongoose - the ODM library to interact with MongoDB on your existing Node.js project.
npm install mongoose
Step 2: Setting up MongoDB
Make sure you have MongoDB running locally or on a cloud-based service like MongoDB Atlas. If you are using a local MongoDB instance, you can start it by running mongod command. Alternatively, if you're using MongoDB Atlas, you’ll need the connection string from your MongoDB cluster to use in your application. For more information please check our YouTube video on How to setup you MongoDB Atlas.
Step 3: Creating a MongoDB Connection with Mongoose
Now that our project is set up, let's establish a connection between Node.js and MongoDB using Mongoose.
In your project folder, create a new folder called utils and add db.utils.js file.
Add the following function after the mongoose options declaration on db.utils.js to create the MongoDB connection:
async function connectDB() {
try {
if(mongoose.connection.readyState != 1) {
await mongoose.connect(dbURi, options);
console.log("Database connected!");
} else {
console.log("Database already connected!");
}
} catch(err) {
console.error(err);
process.exit(1);
}
}
Conclusion
By following these steps, you’ve successfully connected Node.js with MongoDB using Mongoose. This setup is the foundation for building a full-stack application with a robust database management system using MongoDB and Node.js.
File Name: mongodb-nodejs-connection.js
const mongoose = require("mongoose");
const dbURi = "mongodb://localhost:27017";
const options = {
autoIndex: true,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
family: 4
}
async function connectDB() {
try {
if(mongoose.connection.readyState != 1) {
await mongoose.connect(dbURi, options);
console.log("Database connected!");
} else {
console.log("Database already connected!");
}
} catch(err) {
console.error(err);
process.exit(1);
}
}
module.exports = {connectDB}