Integrating MongoDB with Node.js: A Comprehensive Guide

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.

Prerequisite

  • Basic understanding of Node.js, including event-driven architecture and asynchronous programming.
  • Node.js and npm should be installed; download from the official Node.js website if needed.
  • Basic knowledge of MongoDB, including document structure and CRUD operations.
  • MongoDB should be installed locally or accessible via a cloud service like MongoDB Atlas.
  • Proficiency in JavaScript, particularly ES6+ features like promises, async/await, and destructuring.

Steps of Integration

🔶Install Necessary Modules

npm install mongoose express lodash joi
  • Mongoose: This is the key module we’ll use to interact with MongoDB. It provides a powerful schema-based solution for modelling application data and simplifies working with MongoDB collections and documents.
  • Express: A fast and minimalist web framework for Node.js that helps build server-side applications and APIs easily. We’ll use Express to create routes and handle HTTP requests.
  • Lodash: A utility library that makes it easier to work with arrays, objects, and other data types by providing helpful functions like map, filter, and find. It’s widely used for simplifying data manipulation.
  • Joi: A data validation library that helps validate user input or any other data in your Node.js application, ensuring the data conforms to a defined schema before processing it.

🔶Setting Up MongoDB

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:

  1. Download MongoDB
    🔺Head over to the MongoDB official website and download the MongoDB Community Edition for your operating system (Windows, macOS, or Linux).
  2. Install MongoDB
    🔺Follow the instructions provided for your OS to install MongoDB. After installation, ensure that mongod (the MongoDB server) is running. You can start it by running the following command in your terminal:
mongod

This will start the MongoDB server, and by default, it listens on port 27017.

🔶Access MongoDB

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.

🔶Defining a Mongoose Schema and Model

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;
}
  • The token contains the user’s _id, and it’s signed using a private key that’s stored securely in your environment configuration.
  • The token is valid for 1 hour, ensuring limited session time.

Data Validation with Joi

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);
};
  • name: Must be a string between 5 and 50 characters.
  • email: Must be a valid email address with a minimum of 5 characters.
  • password: Must be a string between 5 and 255 characters.

🔶Creating the User Model

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.

Start Building Scalable Apps with MongoDB and Node.js!

Creating User Routes

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;

Running the Application

Now that the routes and MongoDB setup are complete, the final step is to run the app and ensure everything works properly.

🔶Create the Entry File

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}...`));

🔶Add MongoDB URI to Config

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"
}

🔶Start the Application

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.

coma

Conclusion

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 K

Associate Software Engineer

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.

Keep Reading

Keep Reading

Enhance Your Epic EHR Expertise in Just 60 Minutes!

Register Here
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?