In modern web development, handling data efficiently is crucial, and MongoDB has become one of the most popular NoSQL databases. Known for its flexibility and scalability, MongoDB stores data in a document-oriented format, making it ideal for applications with dynamic schemas. Integrating MongoDB with Node.js, a powerful event-driven runtime, allows developers to build fast, scalable, and real-time web applications.
Node.js, with its non-blocking I/O model, pairs seamlessly with MongoDB, enabling efficient handling of large amounts of data. Whether you’re building a RESTful API, a data-heavy web app, or a microservice, MongoDB and Node.js can work together to deliver a robust solution.
In this blog, we’ll walk through the steps to integrate MongoDB into your Node.js project and set up a simple data management system using this powerful combination.
npm install mongoose express lodash joi
You can either install MongoDB locally or set up a cloud instance using MongoDB Atlas. In this section, we’ll cover the local method.
Install MongoDB Locally.
To run MongoDB locally on your machine, follow these steps:
mongod
This will start the MongoDB server, and by default, it listens on port 27017.
Open another terminal window and type the following command to start interacting with MongoDB via the MongoDB shell (mongo):
mongo
Now you are connected to your local MongoDB instance.
Connect Your Node.js Application to local MongoDB.
Once MongoDB is running locally, you can connect your Node.js application using the mongoose library. Here’s how to do it:
Install the required dependencies:
npm install mongoose
1. Use the following code to connect your application to the locally running MongoDB instance:
const mongoose = require('mongoose');
const uri = 'mongodb://localhost:27017/myDatabase'; // replace 'myDatabase' with your database name
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected locally'))
.catch((err) => console.log('MongoDB connection error:', err));
2. This will connect your Node.js app to the local MongoDB server running on localhost at port 27017. Now, your application can interact with the local MongoDB instance.
In MongoDB, documents are stored in a collection, and each document can have a different structure. However, when using Mongoose, we define a schema to enforce structure on these documents. Let’s create a schema for a user model with fields such as name, email, and password.
Defining the User Schema
const mongoose = require("mongoose");
const jwt = require("jsonwebtoken");
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50,
},
email: {
type: String,
unique: true,
required: true,
minlength: 5,
maxlength: 255,
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024,
},
});
Generating JWT (JSON Web Token)
The userSchema also defines a method getJwtToken, which allows us to generate a JWT for authenticated users. We use the jsonwebtoken package to create a signed token, which includes the user’s ID and expires after 1 hour.
userSchema.methods.getJwtToken = function(){
const token = jwt.sign({ _id: this.id }, config.get("jwtPrivateKey"), {
expiresIn: "1h",
});
return token;
}
To ensure the data passed into the user schema is valid, we use the Joi library to define validation rules. The validateUser function checks the name, email, and password fields against specific rules before they are accepted into the database.
const validateUser = (user) => {
const schema = {
name: Joi.string().min(5).max(50).required(),
email: Joi.string().min(5).max(255).required().email(),
password: Joi.string().min(5).max(255).required(),
};
return Joi.validate(user, schema);
};
Finally, we create the User model based on the userSchema and export it so that it can be used across the application.
const User = mongoose.model("User", userSchema);
exports.User = User;
exports.validate = validateUser;
The User model interacts with MongoDB, allowing us to create, read, update, and delete user records, while the validate function ensures that all input data conforms to our defined schema.
In this step, we set up Express routes for user operations, particularly for adding a new user.
We initialize the Express router:
const express = require("express");
const router = express.Router();
const _ = require("lodash");
const { User, validate } = require("../models/user");
const hashPassWord = require("../hash");
We create a basic GET route to confirm the server is running:
router.get("/", (req, res) => {
res.send("Hello");
});
Next, we define a POST route for user registration:
router.post("/addUser", async (req, res) => {
const { error } = validate(_.pick(req.body, ["name", "email", "password"]));
if (error) return res.status(400).send(error?.details[0]?.message);
let user = await User.findOne({ email: req.body.email });
if (user) return res.status(400).send("Email ID already in use!");
user = new User(_.pick(req.body, ["email", "name", "password"]));
user.password = await hashPassWord(user.password);
await user.save();
res.send(_.pick(user, ["email", "name", "_id"]));
});
In this route, we validate the input data, check for existing users, create a new user, hash the password, save the user, and respond with the user’s details (excluding the password for security).
Finally, we export the router:
module.exports = router;
Now that the routes and MongoDB setup are complete, the final step is to run the app and ensure everything works properly.
In your project’s root directory, create an index.js file to start the Express server and connect to MongoDB:
const express = require("express");
const mongoose = require("mongoose");
const config = require("config");
const users = require("./routes/users");
const app = express();
// Middleware to parse JSON
app.use(express.json());
// Route for user operations
app.use("/api/users", users);
// Connecting to MongoDB
mongoose
.connect(config.get("mongoURI"), { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("Connected to MongoDB..."))
.catch((err) => console.error("Could not connect to MongoDB...", err));
// Starting the server
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server running on port ${port}...`));
Ensure you have your MongoDB connection string set in your config folder (or .env file). This can be done in a default.json file like this:
{
 "mongoURI": "your-mongo-db-connection-string",
"jwtPrivateKey": "your-jwt-secret"
}
Run the app by using the following command:
node index.js
This will start the server on the default port (3000). You should see output like:
Connected to MongoDB...
Server running on port 3000...
Now, you can use an API client like Postman to test the /api/users/addUser route by sending a POST request with user data.
Building scalable apps using Node.js and MongoDB integrated offers a strong and adaptable approach. Schema-based models allow us to conveniently handle database activities with the aid of Mongoose. You can easily manage activities like user authentication, data storage, and much more by connecting MongoDB to your Node.js application and configuring it locally or via MongoDB Atlas.
Building reliable full-stack apps that can effectively manage and process massive volumes of data is made possible by this integration.
Nadeem is a front-end developer with 1.5+ years of experience. He has experience in web technologies like React.js, Redux, and UI frameworks. His expertise in building interactive and responsive web applications, creating reusable components, and writing efficient, optimized, and DRY code. He enjoys learning about new technologies.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowEnhance Your Epic EHR Expertise in Just 60 Minutes!
Register HereMindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project. Â
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.Â
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork