Mongoose: How to connect to MongoDB Atlas

Updated: December 30, 2023 By: Guest Contributor Post a comment

Introduction

Connecting your application to a database is one of the foundational steps in backend development. MongoDB Atlas is a cloud-based, fully-managed NoSQL database service by MongoDB. Mongoose is an elegant mongodb object modeling for Node.js that provides a straight-forward, schema-based solution to model your application data. In this guide, we will go step-by-step on how to set up a connection to MongoDB Atlas with Mongoose in a Node.js environment.

Mongoose provides a lot of convenience in data validation, casting and business logic hooks etc. Before creating a connection to MongoDB Atlas with Mongoose, it’s crucial to ensure that both Node.js and npm (node package manager) are installed on your machine. Let’s start the journey of integrating Mongoose with MongoDB Atlas.

Setting up MongoDB Atlas

First, you have to register and set up an account on MongoDB Atlas if you haven’t already. To get started, follow the steps below:

  1. Visit MongoDB Atlas and create an account.
  2. Once logged in, create a new project, and within that project, build a new cluster. For experimenting, you can use the free tier (M0 cluster).
  3. Configure your database access. You should create a new database user that has access to your cluster.
  4. Define the IP address that is allowed to access the database. You can allow access from anywhere for now (0.0.0.0/0), but for production, you should limit it to your application’s IP(s).
  5. Finally, locate the ‘Connect’ button and choose the option that allows you to connect your application. Make sure to note the URI.

Installing Mongoose

npm install mongoose

After installing Mongoose, you’ll be able to require it in your application and start defining schemas and models.

Basic Connection Setup

Once you’ve obtained your MongoDB Atlas connection URI, the next step is to establish a connection to the database using Mongoose. Here’s a basic setup for establishing a connection:

const mongoose = require('mongoose');

mongoose.connect('your-mongodb-atlas-connection-uri', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

mongoose.connection.on('connected', () => {
  console.log('Mongoose connection open to MongoDB Atlas.');
});

mongoose.connection.on('error', (err) => {
  console.error('MongoDB connection error: ' + err);
});

mongoose.connection.on('disconnected', () => {
  console.log('Mongoose disconnected.');
});

This tries to open a connection to your cluster in MongoDB Atlas. Replace ‘your-mongodb-atlas-connection-uri’ with the URI provided by Atlas.

There are several options that you can pass to the connect method to tweak the connection.

With MongoDB Atlas, it is required to use TLS/SSL for connections. To do that, you may need to provide SSL options when you establish a connection. This is how you include them:

It’s crucial to handle reconnections properly in case of database connectivity issues arises. Mongoose allows setting certain options that will handle automatic reconnections.

Using async/await

Beyond simple callbacks, Mongoose supports promises and async/await. This is how you can employ asynchronous functions to handle database connection logic:

const mongoose = require('mongoose');

async function main() {
  await mongoose.connect('your-mongodb-atlas-connection-uri', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: false,
    serverSelectionTimeoutMS: 5000,
    socketTimeoutMS: 45000,
    family: 4 // Use IPv4, skip trying IPv6
  });

  console.log('Mongoose connected to MongoDB Atlas!');
}

main().catch(err => console.error('MongoDB connection error:', err));

Conclusion

In this guide, you’ve learned how to connect to MongoDB Atlas using the Mongoose ODM. We started with setting up MongoDB Atlas and installing Mongoose, then we moved on to establish a simple connection, discussed some advanced connection options like handling SSL/TLS configuration and reconnections, and finally, we refactored the basic setup to use async/await for a cleaner approach. By carefully following through, you are now equipped with the knowledge to integrate a managed MongoDB instance into your Node.js application using Mongoose.

Remember to secure your connection string and credentials properly and tailor the connection options based on your production needs. Happy coding with Mongoose and MongoDB Atlas!