How to Connect to Mongo using Mongoose

Introduction

If you are considering or already using the npm module Mongoose as your driver to interact with MongoDB the first thing you’ll need to do in your Javascript is to setup the connection between Mongoose and your MongoDB service. In this article we take you step-by-step through how to establish and verify the connection so you can move on to the real meat of MongoDB; inserting, updating, and deleting documents.

Prerequisites

  • You should have NodeJS installed. It comes with the node package manager, npm, which we’ll also need.
  • Some command line experience is recommended.

Setup your project using npm

If you haven’t already initialized your project with npm, you’ll want to do that by executing this command which will then keep track of our node dependencies:

npm init

It will prompt you with a bunch of questions with which you can accept the default except you want to make sure that your entry point: (index.js) is the name of the file you want to run your server. In our case it is app.js.

Now if you haven’t already installed the Mongoose npm module you’ll want to do that using this command:

npm install mongoose

Connecting Mongoose to MongoDB

In our particular use case our project folder is called demo and our main server file is called app.js so please follow along as closely as but keep in mind if your path and filenames are different you’ll want to adapt the code to your specific situation.

To connect Mongoose to our MongoDB service in app.js we will need to call the connect() function and give it the URI to our MongoDB service that includes the port number and our database name. The default port number for MongoDB is 27017 unless you change it. So for our example we connect to a demodb using this line of code:

File: /demo/app.js

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/demodb');

Now we want a variable that holds this a connection to our database and we can do that like this:

var db = mongoose.connection;

Of course the variable db can by called anything you want but db is succinct and make sense.

Verify the Connection

To test if the connection is successful there are a couple callback functions that you can use, on() and once().

Let’s see how that would look in code:

db.on('error', console.error.bind(console, 'connectionasdf error:'));
 
db.once('open', function() {
  console.log("Successfully connected to MongoDB!");
});

When we run this the log message will run if we are successfully connected. Let’s run it and see:

$ node app.js
Successfully connected to MongoDB!

And if we want to check that the error case is working we can change to an incorrect port number and see what happens:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27018/demodb'); /* Incorrect Port */

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'Connection Error:'));
 
db.once('open', function() {
  console.log("Successfully connected to MongoDB!");
});
$ node app.js
Connection Error: { Error: connect ECONNREFUSED 127.0.0.1:27018

Conclusion

In this tutorial we showed you which Mongoose functions you can use to connect to you MongoDB service. It’s pretty straightforward code and you’ll most likely only need to write this code once. Of course there are more events that you can hook into and execute callbacks on but these are the basics, letting you know when the connection has been successful or has errored.

Just The Code

If you are already familiar with the all the concepts and just need a quick reminder of the code, here is all the code we used in this tutorial:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/demodb');

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'Connection Error:'));
 
db.once('open', function() {
  console.log("Successfully connected to MongoDB!");
});

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.