Connect MongoDB With node js Using Mongoose[Local and Cloud]

Advertisement

You need a database driver to access a MongoDB database. In our project, we are going t use Mongoose. There are other options like native MongoDB driver.

You first need to install Mongoose in you app. You can run npm install mongoose in the terminal on your project folder.

Once Mongoose is installed, you can proceed on to creating a database.

Creating a MongoDB Database

You can create a MongoDB database online on MongoDB Atlas or you can download and install locally.

Setting Up MongoDB Database on MongoDB Atlas

You first need to create a MongoDB database on MongoDB Atlas by following these steps:

  1. Create an Atlas account
  2. Deploy a Free Tier database cluster
  3. Add your connection IP address to your IP access list
  4. Create a database user for your cluster(https://docs.atlas.mongodb.com/tutorial/create-mongodb-user-for-cluster/). Note down the password for your database user.
  5. To connect to your database cluster, click on the connect button.

  1. Then click on ‘connect your application’.

  1. Finally, copy the uri string provided. We are going to use it later.

Using MongoDB hosted by MongoDB Atlas online reduces frustrations of setting up stuff at the begining so it is a good route to use.

Setting Up MongoDB Database Locally

However, you can also install a local MongoDB database and use it instead of MongoDB Atlas.

These tutorials have detailed information on how to install MongoDB for your specific operating system(OS): Windows, Mac os, and Linux.

Remember to note down the username and password for the database user.

After you have MongoDB installed locally, you need to start it before you can use it. Start MongoDB on your computer by running mongod command on your terminal.

Then, create a database using the command use followed by the database name. Example use list-of-books creates a database called list-of-books.

Keep the terminal open so that you can connect with this database using your app.

The next step is connect Mongoose with local MongoDB database section.

1: Connect to MongoDB Atlas Database using Mongoose

To use mongoose with MongoDB Atlas, start by importing mongoose to your project’s main file. In my case I am working on index.js which is currently empty.

const  mongoose = require("mongoose");

The add the connection string from your mongoDB database. To get this connection string, click on the connect button on your MongoDB database. Copy the connection string.

const uri = mongodb+srv://mydatabaseadmin:<password>@cluster0.p198l.mongodb.net/?retryWrites=true&w=majority;

Change the <password> bit with your own database password that you set during the dabatase creation process. So if you database password was “honeymoonisoverin100years”, your uri should be:

const uri = mongodb+srv://mydatabaseadmin:honeymoonisoverin100years@cluster0.p198l.mongodb.net/?retryWrites=true&w=majority;

Connecting to the database:

// Declare a variable named option and assign optional settings
const  options = {
  useNewUrlParser:  true,
  useUnifiedTopology:  true
};

// Connect MongoDB Atlas using mongoose connect method
mongoose.connect(uri, options).then(
  () => {
    console.log("Database connection established!");
  },
  (err)  => {
      console.log("Error connecting Database instance due to:", err);
  }
);

You should see:

If you see Database connection established, you might see the following error.

Error connecting Database instance due to: MongooseServerSelectionError: connection <monitor> to 54.149.0.26:27017 closed

MongoDB Atlas is blocking the connection due to the IP address. To stop this, go to MongoDB atlas and add the following to your ip address list.

0.0.0.0

This will allow you to access the database from any computer. You can change this later to point to your production server when you deploy your application.

It is a good practice to hide passwords using an enviroment variable saved in a .env file.

I create a new entry named dbpass in my .env file.

#Database Config
DBPASS=honeymoonisoverin100years

Then modify your uri string

const  uri = "mongodb+srv://databaseadmin:" + process.env['DBPASS'] + "@cluster0.p198l.mongodb.net/?retryWrites=true&w=majority";

It is also a good practice to create a seperate file for connecting to database so lets do that.

Create a new file connectdb.js. Put the mongoose related code in connectdb.js.

const  mongoose = require("mongoose");

const  uri = "mongodb+srv://databaseadmin:" + process.env['DBPASS'] + "@cluster0.p198l.mongodb.net/?retryWrites=true&w=majority";


// Declare a variable named option and assign optional settings
const  options = {
  useNewUrlParser:  true,
  useUnifiedTopology:  true
};

// Connect MongoDB Atlas using mongoose connect method
mongoose.connect(uri, options).then(
  () => {
    console.log("Database connection established!");
  },
  (err)  => {
      console.log("Error connecting Database instance due to:", err);
  }
);

Then, import this connection into your main file index.js.

// Import DB Connection
require("./config/db");

Using MongoDB atlas reduces frustrations of setting up stuff at the begining so it is a good route to use. If you decide to keep learning and using MongoDB, you can install a local database and use it instead of MongoDB Atlas.

2. Connect to MongoDB Local Database Using Mongoose

Start by creating a .js file. You will use this file to create database connection. Ensure your file name indicates what the files does for future reference. So in my case I call it connectdb.js.

Import mongoose in your connectdb.js file.

const  mongoose = require("mongoose");

Add the url to your database. The url starts with the MongoDB url mongodb://127.0.0.1:27017/ followed by the name of the database you want to connect to.

const url = ‘mongodb://127.0.0.1:27017/list-of-books’;

Then, connect to MongoDB using:

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

To check whether your local MongoDB connection works, add the following code at the end of your file.

const db = mongoose.connection
db.once('open', _ => {
  console.log('Database connection established at', url)
})

db.on('error', err => {
  console.error('Database connection error due to:', err)
})

Your final local code should be:

const  mongoose = require("mongoose");

const url = 'mongodb://127.0.0.1:27017/list-of-books';

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

const db = mongoose.connection
db.once('open', _ => {
  console.log('Database connection established at', url)
})

db.on('error', err => {
  console.error('Database connection error due to:', err)
})
author's bio photo

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.