DEV Community

Cover image for Connecting Node.js To MongoDB Atlas Using Mongoose: A Step-by-Step Guide
Luqman Shaban
Luqman Shaban

Posted on

Connecting Node.js To MongoDB Atlas Using Mongoose: A Step-by-Step Guide

In an era driven by data, where information reigns supreme, harnessing the potential of Node.js and MongoDB Atlas has become a cornerstone for developers. As Node.js empowers the creation of scalable, high-performance applications, MongoDB Atlas offers a robust, cloud-based database solution. And what connects these powerful technologies seamlessly? Mongoose, the elegant modeling library for MongoDB and Node.js. In this article, we will delve into the art of connecting Node.js to MongoDB Atlas using Mongoose, unraveling the steps, techniques, and best practices to unlock a world of endless possibilities in modern web development.

Let's begin by creating our project folder and initializing a package.json file:

mkdir nodejs-mongodb 
cd nodejs-mongodb 
npm init -y
Enter fullscreen mode Exit fullscreen mode

Executing the following command to create a file and a folder:

touch index.js
mkdir config
Enter fullscreen mode Exit fullscreen mode

Next, install the necessary dependencies:
npm i express mongoose dotenv nodemon

Open the folder in Vscode: code .

In the root folder, we need to create a .env folder that will store our Atlas connection string. If you don't have an Atlas account yet, create one and deploy a cluster. Navigate to your cluster and click on connect:

Image of mongodb atlas

Choose the first option Drivers:

Image of mongodb atlas

Choose the highest version of Node.js and copy your connection string.
Image of mongodb atlas

In Vscode, open the .env file and create a variable DB_STRING and paste your connection string:

DB_STRING=mongodb+srv://blogall:<your user password>.@cluster0.oxdey6v.mongodb.net/?retryWrites=true&w=majority

Make sure to exclude the <> tags after inserting your password.

Open the config folder and create a db.js file and import the following:

import dotenv from 'dotenv';
import mongoose from 'mongoose';
Enter fullscreen mode Exit fullscreen mode

Load the environment variable and store the connection string in a variable:

dotenv.config()

const connectionString = process.env.DB_STRING
Enter fullscreen mode Exit fullscreen mode

Create a function that connects to the atlas database and export it:

const connectToDB = async () => {
    try {
        await mongoose.connect(connectionString, {
            autoIndex: true
        })
        console.log('Connected to Mongodb Atlas');

    } catch (error) {
        console.error(error);
    }
}

export default connectToDB
Enter fullscreen mode Exit fullscreen mode

The provided code snippet is an arrow function named connectToDB, which is responsible for establishing a connection to MongoDB Atlas using Mongoose in a Node.js application. Here's a breakdown of what the code does:

The connectToDB function is defined as an asynchronous function using the async keyword. This allows the use of await inside the function to handle promises in a more readable and synchronous-like manner.

Inside the function, there is a try-catch block, which is used for error handling. The code inside the try block attempts to establish a connection to the MongoDB Atlas database.

The connection is established using themongoose.connect()method, which takes two parameters: the connectionString and an options object. In this case, the options object includes autoIndex: true, which enables automatic indexing of MongoDB documents for better query performance.

If the connection is successful, the code inside the try block executes, and a success message, "Connected to Mongodb Atlas," is logged to the console.

If an error occurs during the connection attempt, the catch block is executed. The error object is logged to the console using console.error().

Finally, the connectToDB function is exported as the default export using export default. This allows other parts of the application to import and use this function for establishing the database connection.

Here's how the file looks:

import dotenv from 'dotenv';
import mongoose from 'mongoose';

dotenv.config();

const connectionString = process.env.DB_STRING;

const connectToDB = async () => {
    try {
        await mongoose.connect(connectionString, {
            autoIndex: true
        })
        console.log('Connected to Mongodb Atlas');

    } catch (error) {
        console.error(error);
    }
}

export default connectToDB
Enter fullscreen mode Exit fullscreen mode

In index.js, import the following:

import express from 'express';
import connectToDB from './config/db.js';
Enter fullscreen mode Exit fullscreen mode

Create an instance of express, and call connectToDB function:

const app = express();

connectToDB()
Enter fullscreen mode Exit fullscreen mode

To run the server add the following code:

app.listen(3000, () => {
    console.log('Server started on port 3000');
});
Enter fullscreen mode Exit fullscreen mode

The above snippet will run your application on localhost:3000 in the browser.
Here's how the file looks:

import express from 'express';
import connectToDB from './config/db.js';
import router from './routes/UserRoute.js';

const app = express();
connectToDB()

// Start the server after successfully connecting to the database
app.listen(3000, () => {
    console.log('Server started on port 3000');
});
Configure the package.json file and add the following:
"type": "module", "scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "nodemon app.js"
},
Enter fullscreen mode Exit fullscreen mode

Open your terminal in Vscode and execute the following command:npm start
You should see the following:
Server started on port 3000
Connected to Mongodb Atlas

In this article, we delved into the art of connecting Node.js to MongoDB Atlas using Mongoose, unraveling the steps, techniques, and best practices to unlock a world of endless possibilities in modern web development.

Starting from setting up the project folder and initializing the package.json file, we walked through the process of installing the necessary dependencies. We then created the .env file to store the Atlas connection string and established the database connection in the config/db.js file using the connectToDB function.

Moving on, we imported the required dependencies in the index.js file, created an instance of Express, and called the connectToDB function to establish the database connection. We also added code to start the server and configured the package.json file to enable running the application using npm start.

Upon executing the command npm start in the terminal, we successfully started the server on port 3000 and received the confirmation that we were connected to MongoDB Atlas.

By following these step-by-step instructions, you are now equipped with the knowledge and tools to connect Node.js to MongoDB Atlas using Mongoose. You can further expand upon this foundation to build powerful, data-driven applications that leverage the capabilities of both Node.js and MongoDB Atlas.

Happy coding!

Connect With me:
LinkedIn
Twitter

Top comments (0)