How to connect MongoDB using mongoose in Node JS

Mongoose.js is a Node.js library that connects your MongoDB clusters or collections to your Node.js application. You can use it to construct schemas for your documents. When it comes to generating and working with schemas, Mongoose has a lot to offer. We’ll look at how to connect a MongoDB instance to a Node.js application in this tutorial.

What is MongoDB

MongoDB is one of the most popular No-SQL databases in use today among developers. Instead of SQL objects, NoSQL databases allow developers to transmit and receive data as JSON documents. Mongoose can be used to work with MongoDB in a Node.js application.

Prerequisites

Before we go any further, you’ll need the following:

  • You have Node.js installed on your computer.
  • On your PC, there is a MongoDB instance running. If you want to utilize Mongo DB Atlas, you won’t need this.
  • Some experience with Node.js and Express.js is required.

Setting Up Environment

  • Create an empty directory with any name you want.
  • Open the folder with any code editor. I would like to prefer VS Code.
    1. You can download vs code from here.  https://code.visualstudio.com/
  • Now press ctrl + shift + ~ to open terminal.
  • Now type npm init -y and hit enter. It will create package.json file and install necessary node modules
  • Now type npm install express nodemon cors dotenv mongoose
  • Now create an empty file namely server.js and put below code in it.
const express = require("express");
const cors = require("cors");
const dotEnv = require("dotenv");

const app = express();

//registering middlewares
dotEnv.config();
app.use(cors());
app.use(express.json());

//listening to port
const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`Server is running on ${port}`);
});

Creating the Connection

  • In your root directory, create folder “config”
  • Create an empty file, “db.js”
  • Create .env file in root directory and add variable MONGO_URI = url here
    • Directory Structure:
  • If you want to connect db locally replace MONGO_URI with mongodb://localhost:27017/usersdb 

Where usersdb is the database name, you can give yours.

Again, click on Create Cluster Button

Wait for few minutes, and then following dashboard will appear

Click on connect and choose your application.

Copy the URL and add your name and password in url, which you have set when creating cluster, and put it .env file.

Inside config folder, In db.js put the following code

const mongoose = require("mongoose");
const getConnection = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    if (conn) {
      console.log(`MongoDB Connected on ${conn.connection.host}`);
    } else {
      console.log("Failed to connect DB");
    }
  } catch (error) {
    console.log(`Failed with error: ${error.message}`);
  }
};

module.exports = getConnection;

Now update server.js file as 

const express = require("express");
const cors = require("cors");
const dotEnv = require("dotenv");
const getConnection = require("./config/db");
const app = express();

//registering middlewares
dotEnv.config();
app.use(cors());
app.use(express.json());

//connecting TO DB
getConnection();

//listening to port
const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`Server is running on ${port}`);
});

In package.json file add under scripts, 

Finally, go to the terminal, type npm start, and hit enter.

Conclusion

In conclusion, we connected to MongoDB using mongoose in Node JS. Now you can easily read and write to the database. You can always find more useful articles here.

Scroll to Top