DEV Community

Cover image for MongoDB Connection using Mongoose
Vinit Gupta
Vinit Gupta

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 :

const mongoose = require("mongoose");
Enter fullscreen mode Exit fullscreen mode

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.

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);
  });
Enter fullscreen mode Exit fullscreen mode

Now the question is what are these terms :

    useNewUrlParser: true,
    useFindAndModify: false,
    useUnifiedTopology: true
Enter fullscreen mode Exit fullscreen mode

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

useNewUrlParser: true
Enter fullscreen mode Exit fullscreen mode

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)