How to Use the Mongoose Connect Method

Introduction

MongoDB is a NoSQL database that stores data in the JSON format. It is one of the most popular databases in the modern web development world. MongoDB is often used with software stacks such as MERN and MEAN. Along with MongoDB, NodeJS is also an important part of these software stacks. MongoDB only creates the database, but it does not connect it with the other part of the application. To connect MongoDB, we can use mongoose. Mongoose provides the connect() function that helps in establishing the MongoDB with the application. In this article, we will understand how to use the connect() method to connect the application with MongoDB.

Installing mongoose and express

Create a new file and name it “server.js” and install express.

npm install express --save

Then, we need mongoose.

npm install mongoose --save

We are ready to go. Let import the express and mongoose module in our file.

const express = require("express");
const mongoose = require("mongoose");

connect()

Now, let’s understand the connect() method.

The connect() method has one mandatory parameter. It is the link to the local MongoDB database.

const link = "mongodb://127.0.0.1:27017/kennels";

‘27017’ is the port where MongoDB runs locally and “kennels” is the name of the database we are connecting.

Then, we can use the instance of mongoose that we created earlier to invoke the connect() method and pass the link to it.

mongoose.connect(uri);

Next, we will use the listen() method to run the server.

app.listen(4000, function() {
  console.log("Server is running on Port: 4000");
});

This is how server.js looks now.

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const uri = "mongodb://127.0.0.1:27017/kennels";
mongoose.connect(uri);

app.listen(4000, function() {
  console.log("Server is running on Port: 4000");
});

Let’s run the server.

node server

Image from Gyazo

The connection is established successfully and the server is running on port 4000. But a warning appears. We have to enable useUnifiedTopology and useNewUrlParser to remove this warning. Pass the following object as the second parameter.

{ useUnifiedTopology: true, useNewUrlParser: true}

Let’s run the server again and check if any warning appears or not.

Image from Gyazo

Everything is fine! No warning appears.

Conclusion

Thank you for reading this article on how to use the connect method of Mongoose to connect to the MongoDB database. We hope you can apply what you’ve learned to your specific application.

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.