Introduction

In this article, we'll go over how to connect a MongoDB cloud database created on Atlas using Node.js and the Mongoose NPM package.

MongoDB is a document-based and non-SQL database that is great for building modern applications. And Atlas allows you to quickly get a database running in the cloud, handles all the security and headache-inducing aspects of managing a database, and has a generous free-tier for you to use as well.

If you don't have a MongoDB database creating on Atlas, we'll show you how to do that in this guide.

And before you begin this guide, you'll need to have Node.js and NPM installed on your local development machine. We created an installation guide if you need help getting Node.js and NPM installed on your machine.

Let's get started!

Connect to the Database Using Node.js

With a MongoDB database creating on Atlas, you can connect to it using Node.js. We'll use the Mongoose NPM package to interact with the MongoDB database.

First, you'll need to create a Node.js application if you don't already have one.

You can quickly do this by creating a new directory for your project (replace your-project with the name you want to use):

    
      mkdir your-project
    
  

And cd into your new project directory:

    
      cd your-project
    
  

Then, run the npm init -y command to create a package.json file and initiate a new Node.js application in the root of your project:

    
      npm init -y
    
  

Now, you can create a new index.js file that will serve as the entry point for your application and where we'll add your code:

    
      touch index.js
    
  

To connect and interact with your database, we'll use the Mongoose NPM package.

You can install it to your project with this command:

    
      npm install --save mongoose
    
  

When that's done installing, open the index.js file in your favorite code editor.

First, import the mongoose NPM package at the top of the file:

    
      const mongoose = require("mongoose")
    
  

Now mongoose will be available for you to use in the code.

Now, you'll need the connection string provided by Atlas. It should look similar to this:

    
      mongodb+srv://<username>:<password>@test.pxqht.mongodb.net/<dbname>?retryWrites=true&w=majority
    
  

Make sure you use the connection string provided to you by Atlas and replace the username, password, and dbname items with the values you configured for your database.

The scheme for the connection string is as follows:

    
      mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
    
  

Here is a quick explanation for each item in the string:

  • mongodb://: a required prefix to identify that this is a string in the standard connection format.
  • username:password@: authentication credentials.
  • host[:port]: the host (and optional port number) where database instance is running.
  • /defaultauthdb: the authentication database to use if the connection string includes username:password@ authentication credentials. This is an optional item.
  • ?<options>: a query string that specifies connection specific options as <name>=<value> pairs. See Connection String Options for a full description of these options. This is an optional item.

You can connect to your MongoDB database with this code (replace "YOUR_CONNECTION_STRING" with your connection string):

    
      const mongoString = "YOUR_CONNECTION_STRING"

      mongoose.connect(mongoString, {useNewUrlParser: true})

      mongoose.connection.on("error", function(error) {
        console.log(error)
      })

      mongoose.connection.on("open", function() {
        console.log("Connected to MongoDB database.")
      })
    
  

Using your connection string, we connect to the MongoDB database using the mongoose.connect() method. We also add the additional option of useNewUrlParser to help avoid deprecation warnings that may arise.

Then, we added some code to listen for both any errors to occur and the successful connection to the database. We use the mongoose.connection.on() method to listen for those specific events. If an error occurs after the initial connection is made, we want to console.log() the error so we understand what happened. And we also want to log a success message when the application initially connects to the database.

Make sure you save the index.js file after making those changes.

For your reference, the entire index.js file should look like this:

    
      const mongoose = require("mongoose")

      const mongoString = "mongodb+srv://<username>:<password>@test.pxqht.mongodb.net/<dbname>?retryWrites=true&w=majority"

      mongoose.connect(mongoString, {useNewUrlParser: true})

      mongoose.connection.on("error", function(error) {
        console.log(error)
      })

      mongoose.connection.on("open", function() {
        console.log("Connected to MongoDB database.")
      })
    
  

Now, we can start the application. If you don't have one already, you'll need to add an npm start script to your package.json file.

To do so, open your package.json file and add this JSON code to the "scripts" section:

    
      "start": "node index.js"
    
  

Then, you can start your application with this command:

    
      npm start
    
  

If the connection to your MongoDB database is successful, this output should show in your terminal:

    
      Connected to MongoDB database.
    
  

If you run into errors, verify that the code matches what was provided above and that your connection string username and password credentials match what you created on the Atlas website dashboard.

If everything went as planned, you should now be connected to your MongoDB Atlas cloud database!

Conclusion

There you have it! Your Node.js application should now be connected to your MongoDB cloud database on Atlas.

Thanks for reading and happy coding!