Connect MongoDB using Mongoose


In this post, we are going to learn how to install and establish a connection to MongoDB using mongoose.

Install Mongoose

// Command to install Mongoose 
$ npm install mongoose

// To install a particular version of Mongoose
$ npm install [email protected](version number)

Connection to MongoDB

To establish a connection to MongoDB first we need to import mongoose module to our project which is available in the NPM registry. Once we install mongoose we will have all methods which are available in mongoose.

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/play')
    .then(() => console.log('Connected to database'))
    .catch(err => console.log('could not connect to the mongo db'));

In the above code, I mentioned localhost but it will be changed based on where you are deploying code. By using connect method we can connect our application to Mongo DB.