DEV Community

Cover image for MongoDB Node.js Connection
yactouat
yactouat

Posted on

MongoDB Node.js Connection

So you want to connect to a MongoDB instance from Node.js? Here's how to do it easily.

Prerequisites

  • Node.js installed
  • Docker Desktop installed
  • I assume you're working on some project empty folder.

Let's spin up a MongoDB instance

Let's put together a docker-compose file to spin up a MongoDB instance.

# creating a volume here allows us to persist data even if the container is deleted
volumes:
  mongodb_data:

services:
  mongodb:
    # pulling an image from hub.docker.com
    image: mongo:6.0.7
    restart: always
    ports:
      # binding to the localhost (left-hand side) and the container (right-hand side) ports
      - 27017:27017
    # attaching the volume to the container
    volumes:
      - mongodb_data:/data/db
Enter fullscreen mode Exit fullscreen mode

Now, when your run docker-compose up -d, you should have a MongoDB instance running on your machine on port 27017.

Scaffold our NodeJS API

Initialize your NodeJS project with npm init -y and install the following dependencies:

npm i express mongodb
npm i -D nodemon
Enter fullscreen mode Exit fullscreen mode

express is a popular web framework for NodeJS. nodemon is a tool that will restart your NodeJS server whenever you make changes to your code.

Let's add start scripts to our package.json file:

"scripts": {
  "dev": "nodemon api.js",
  "start": "node api.js"
}
Enter fullscreen mode Exit fullscreen mode

If you want to run your server in development mode, you can run npm run dev, this will restart the server every time you make changes to the NodeJS API code.

mongodb is the official MongoDB driver for NodeJS.

You should git ignore the node_modules folder right away at this point.

Now let's create an api.js file in the root of our project and add the following code:

const express = require("express");

const app = express();

app.get("/", (req, res) => res.send("API Running"));

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
Enter fullscreen mode Exit fullscreen mode

If you run npm run dev and navigate to localhost:5000 in your browser, you should see the message "API Running".

Connect to MongoDB from NodeJS

To connect to any type of database, you would need a client, MongoDB is no exception to this. Let's create a mongo.js file and add the following code:

// getting the client class from the official mongodb driver
const { MongoClient } = require('mongodb');

/**
 * 
 * connect to a MongoDB database and return the db client instance
 * 
 * @param {string} dbUrl - localhost would be mongodb://localhost:27017
 * @param {string} dbName 
 * @returns {MongoClient|null}
 */
module.exports = async function connectToMongoDb(dbUrl, dbName) {
    const client = new MongoClient(dbUrl);
    try {
        await client.connect();
        console.log('Connected successfully to server');
        // returning the client object
        return client;
    } catch (error) {
        console.error(error);
        // returning null if there is an error while connecting
        return null;
    }
}
Enter fullscreen mode Exit fullscreen mode

We are ready for the final step: connecting to the MongoDB instance from our NodeJS API. Let's modify our api.js file:

const express = require("express");

// getting the connectToMongoDb function from mongo.js
const getMongoClientObj = require("./mongo");

const app = express();

app.get("/", async (req, res) => {
    // arbitrary database name
    const dbName = "test";
    const dbObj = await getMongoClientObj("mongodb://localhost:27017", dbName);
    // sending back a JSON response
    res.json({ 
        msg: "Welcome to the API connected to MongoDB!", 
        data: {
            dbIsup: dbObj != null // this way we can check if the db is up or not
    }});
    // if there is a db connection, we can get the server status
    if (dbObj != null) {
        dbObj.db(dbName).admin().serverStatus().then((info) => {
            console.info("INFO ABOUT AVAILABLE AND CURRENT CONNECTIONS: ", info.connections);
            // ! comment the line below and see the current connections count pile up ;)
            dbObj.close();
        });
    }
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
Enter fullscreen mode Exit fullscreen mode

Load environment variables from a .env file

Until now, we have loaded the database URL and the database name directly into our code. This is not a good practice because:

  1. We don't want to commit sensitive information to our git repository.
  2. We don't allow for modularity, we would have to change the code if we want to connect to a different database.

Let's create a .env file in the root of our project and add the following lines:

DB_URL=mongodb://localhost:27017
DB_NAME=test
Enter fullscreen mode Exit fullscreen mode

Let's install the dotenv package:

npm i dotenv
Enter fullscreen mode Exit fullscreen mode

This package will allow us to read and load environment variables from the .env file we've created. At the top of the api.js file, let's add the following line:

require("dotenv").config();
Enter fullscreen mode Exit fullscreen mode

And now, instead of hardcoding the database URL and the database name, we can use the environment variables:

// ...
const dbName = process.env.DB_NAME;
const dbObj = await getMongoClientObj(process.env.DB_URL, dbName);
// ...
Enter fullscreen mode Exit fullscreen mode

Don't forget to add the .env file to your .gitignore file.

Also, for better developer experience, think about adding a .env.example file to your repository, this way, other developers can easily know which environment variables they need to add to their .env file:

DB_URL=mongodb://localhost:27017
DB_NAME=test
Enter fullscreen mode Exit fullscreen mode

As you noticed, the contents are the same as the .env file here, since we're only working locally; but this might prove to be useful later when you'll work on various environments (dev, staging, production, etc).

Wrapping it up

Now you're all set to build your NodeJS apps using MongoDB locally. See ya then !
You can see the code for this tutorial here.

Top comments (0)