How to Connect MongoDB to Node.js Express Using Mongoose

Robin
Updated on June 10, 2023

We use the Mongoose library when we want to connect the MongoDB database to our Node.js and Express server. Most of the time, beginners get confused between MongoDB and Mongoose.

MongoDB is a NoSQL database system that provides a scalable and flexible data storage solution. It is the database to store data. You can also update and query the data.

On the other hand, Mongoose is an Object Data Modeling (ODM) library for Node.js that simplifies the interaction with MongoDB by providing a schema-based approach, validation rules, and additional features.

In simple words, Mongoose is a tool that helps you to integrate your Node.js server with the MongoDB database by creating connections, defining schemas for data, creating relationships, allowing different ways to query and update data, etc.

In this post, I will show you the best way to connect MongoDB database to the Node.js Express server using the Mongoose library.

Connecting MongoDB to Node.js Express Server Using Mongoose

In order to connect your MongoDB database to your Node.js server, you need to follow 2 simple steps. First, install the Mongoose package to your project. Second, call the mongoose.connect() method with the connection URL.

This is the syntax:

          mongoose.connect(url, options)
        

The Mongoose package has the connect() method. This method has 2 parameters. The first parameter is the connection URL. The second parameter is the options (optional). This is an object with some properties to configure the connection.

Also Read: How to Sanitize HTML in Node.js Express Server Properly


Step 1: Installing Express and Mongoose Package

To use this package, you have to install it in your project. You can install it using both the npm and yarn package managers.

Use the following command if you are using NPM:

          npm install express mongoose
        

If you are using Yarn, use this:

          yarn add express mongoose
        

Here I am installing both Express and Mongoose packages. If you already have Express installed in your project, you just have to install the Mongoose package.

Also Read: How to Use ES6 Modules Import and Export Syntax in Node.js


Step 2: Integrating MongoDB with Node.js Server

I have a server.js file where I am importing express and mongoose packages using the require() function. I am also calling the express() function to get the Express application.

          const express = require('express')
const mongoose = require('mongoose')

const app = express()
        

Before starting the server, you need to make sure that the database is successfully connected. Because if the database doesn't work, your application won't be able to do anything.

That's why it is better to call the listen() method after calling the mongoose.connect() method. You can use a MongoDB database in 2 ways.

  • Install MongoDB locally on your computer.
  • Create a database in the cloud using MongoDB Atlas.

You have to use different connection URLs in the mongoose.connect() method based on the database type.

Also Read: Get Query Strings and Parameters in Express Routes on NodeJS


Local Database Connection

When you want to connect a local MongoDB database to your Node.js application, the connection URL will be different.

This is the URL structure:

          mongodb://localhost:27017/usersdb
        

This connection string specifies the details for connecting to a MongoDB database. Here's a breakdown of the components:

  • mongodb://: This is the protocol or scheme that indicates the type of database being connected to (MongoDB in this case).
  • localhost: It refers to the hostname or IP address of the server where the MongoDB database is running. In this case, it indicates that the database is located on the local machine.
  • :27017: This is the port number on which the MongoDB server is listening for incoming connections. The default port for MongoDB is 27017.
  • /products: It specifies the name of the MongoDB database to connect to. In this case, it indicates that the connection is made to a database named "products". If you want to connect to a different database, change it with the name of your database.

To establish a connection, you have to use this URL string in the mongoose.connect() method to connect to the MongoDB server running on the local machine.

          const express = require('express')
const mongoose = require('mongoose')

const app = express()

// ...

// Connecting to MongoDB
mongoose
    .connect('mongodb://localhost:27017/products', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    .then(() => {
        console.log('Connected to MongoDB database')

        // Starting NodeJS server
        app.listen(3000, () => {
            console.log('Server listening on port 5000')
        })
    })
    .catch((err) => {
        console.log(err)
        console.log('Database connection failed')

        process.exit(1)
    })
        

Call the connect() method with the connection string as the first argument and an object with some options as the second argument.

Set the options useNewUrlParser and useUnifiedTopology to true. These options ensure that Mongoose uses the new URL parser and unified topology engine for managing connections.

We will talk about the other options later in this article.

This method returns a promise. So inside the .then() block, call app.listen() to start the Express server on port 3000. It will ensure that your application will start after successfully connecting to the database.

If an error occurs during the database connection, you can handle it in the .catch() block. Like showing an error message in the console and calling process.exit(1) to exit the Node.js process with a non-zero exit code.

Also Read: Getting Data From req.body in Node.js & Express Server


MongoDB Atlas Database Connection

On the other hand, if you are using a cloud database in MongoDB Atlas, the connection string will be different than the local database.

This is the URL structure:

          mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/<database-name>?retryWrites=true&w=majority
        

For example:

          mongodb+srv://maxngc:3VqZLRk9dw@ecom.tqliv.mongodb.net/products?retryWrites=true&w=majority
        

This connection string is specifically designed for connecting to a MongoDB Atlas database using the SRV (Service) record format. Here's a breakdown of the components:

  • mongodb+srv://: This is the protocol or scheme that indicates the type of database being connected to, specifically MongoDB Atlas using the SRV record format.
  • <username>:<password>@: These are the credentials for accessing the MongoDB Atlas database. You would replace <username> and <password> with your actual MongoDB Atlas credentials.
  • <cluster-name>.mongodb.net/: This portion represents the MongoDB Atlas cluster name, which is a logical grouping of database servers that collectively store your data.
  • <database-name>: It specifies the name of the MongoDB database within the cluster that you want to connect to.
  • ?retryWrites=true&w=majority: These are query parameters that specify certain options for the MongoDB connection. retryWrites=true enables retryable writes, which ensures that write operations are automatically retried in case of errors. w=majority specifies that write operations must be acknowledged by a majority of the replica set members before they are considered successful.

To establish a connection, you would replace <username> and <password> with your actual MongoDB Atlas credentials, <cluster-name> with the name of your Atlas cluster, and <database-name> with the desired database name.

          const express = require('express')
const mongoose = require('mongoose')

const app = express()

// ...

// Connecting to MongoDB
mongoose
    .connect(`mongodb+srv://${process.env.USERNAME}:${process.env.PASSWORD}.tqliv.mongodb.net/products?retryWrites=true&w=majority`, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    })
    .then(() => {
        console.log('Connected to MongoDB database')

        // Starting NodeJS server
        app.listen(3000, () => {
            console.log('Server listening on port 5000')
        })
    })
    .catch((err) => {
        console.log(err)
        console.log('Database connection failed')

        process.exit(1)
    })
        

Username and password are sensitive information. Directly putting those in your code is not a good idea. You should store them in the environment variables and access the values using process.env in your application.

Also Read: Easiest Way to Set & Use Environment Variables (.env) in Node.js


Mongoose Connection Options

When establishing a connection to a MongoDB database using Mongoose, you can pass an options object to the mongoose.connect() or mongoose.createConnection() method to configure various settings. Here are some commonly used Mongoose connection options:

  • useNewUrlParser: It is used to parse the MongoDB connection string using the new URL parser. Set it to true to enable this feature.
  • useUnifiedTopology: This option enables the new MongoDB driver's unified topology engine for managing connections. Set it to true to use the new engine.
  • autoIndex: When set to true, Mongoose automatically builds indexes defined in your models during the connection process. However, in production environments, it is generally better to manually define indexes.
  • poolSize: It sets the maximum number of sockets that can be opened for the MongoDB connection. Increasing this value can help handle higher traffic loads, but be mindful of the system's limitations.
  • connectTimeoutMS: This option specifies the connection timeout duration in milliseconds. If the connection to the MongoDB server takes longer than this timeout, an error will be thrown.
  • socketTimeoutMS: It sets the maximum amount of time in milliseconds that a MongoDB operation can take before it's considered timed out.

These are just a few examples of the connection options available in Mongoose. You can explore the Mongoose documentation for a comprehensive list of available options and their descriptions.

Also Read: Node.js Cluster: Improve Server Performance with Clustering


Conclusion

MongoDB and Mongoose play distinct roles in the context of building applications with Node.js and Express. MongoDB serves as a scalable and flexible NoSQL database system, while Mongoose acts as an Object Data Modeling (ODM) library.

The tutorial has provided a step-by-step guide for establishing a MongoDB connection, configuring options, and demonstrating how to integrate MongoDB and Node.js using Mongoose.

Related Posts