DEV Community

Cover image for MongoDB Connection using Mongoose
Shahnawaz Alam
Shahnawaz Alam

Posted on

 

MongoDB Connection using Mongoose

An important step in the process of Development is connecting with the database. This has been made easy with mongoose, which is an npm dependency.

After you have initialized your express app, install mongoose using the following npm command :

npm install mongoose

Mongoose can be used in 3 simple steps :

Setting up a port

Since mongoDB runs on a server, we need to run a mongoDB server locally. If you have mongoDB installed locally, just head to your preferred terminal and run :

mongod

Your mongoDB server is up and running on port: 27017

Importing Mongoose

You can import and use mongoose in 2 places :

In the server.js file

You can import and use mongoose in the main server file itself :
javascript
const mongoose = require("mongoose");

In a Separate Database Folder

You can also implement the modular approach where you can create a separate db folder and setup connection inside it in a connections.js file.

Connecting To Server

The final step is to initialize and setup the mongoDB connection.
The process is to initialize the mongoose connection and listen for the result returned.

javascript
const mongoose = require("mongoose");

mongoose
.connect(process.env.DB_URL, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then((result) => {
console.log("Database connected at port : "+process.env.DB_URL);
})
.catch((err) => {
console.log(err);
});

Now the question is what are these terms :
javascript
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true

These are optional arguments being passed to the connection method.

1. useNewUrlParser

The underlying MongoDB driver has deprecated their current connection string parser. Because this is a major change, they added the useNewUrlParser flag to allow users to fall back to the old parser if they find a bug in the new parser. You should set
javascript
useNewUrlParser: true

unless that prevents you from connecting.

2. useFindAndModify

true by default. Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify().

findOneAndUpdate allows for just updates - no deletes or replaces etc.

findAndModify can do a lot more including replace, delete and so on.

3. useUnifiedTopology

false by default. Set to true to use the MongoDB driver's new connection management engine. This option should always be set to true, except for the unlikely case that it prevents you from maintaining a stable connection.

There we go! We have successfully setup a mongoDB connection.
Happy Hacking!!

Top comments (0)