DEV Community

Cover image for How to connect MongoDB with NodeJS Application!
Kunguma Sakthivel K
Kunguma Sakthivel K

Posted on

How to connect MongoDB with NodeJS Application!

In this blog, I going to show how to connect with MongoDB in NodeJS application.

First create root directory folder and go to terminal and install required packages.

npm install express nodemon mongodb mongoose cors dotenv

These packages are required to setup the mongoDB server.

MongoDB Account Setup

  • First, create a mongoDB atlas account and create a cluster.
  • After creating cluster, go to Data Service and click on connect

mongoDb ui

  • After clicking connect, then popup window will appear

![mongoDb ui]](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96gz3lje8sg19sinevoe.png)

  • Click on driver to get your mongoDB connection string which look like mongodb+srv://<username>:<password>@cluster0.5hjxnse.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0

Folder setup and DB connection code!

  • Now create a root folder and name it as your wise. Eg: mongo-connection
  • Then create a file called index.js and past the bellow code
const express = require('express');
const cors = require('cors');
const { connection } = require('./db');
require('dotenv').config();
const port = process.env.PORT 
const app = express();
app.use(cors());
app.use(express.json());

app.get('/', (req, res) => {
    res.send({
        message: 'api is working'
    })
})

app.listen(port, async()=> {
    try{
        await connection
        console.log('db is connected')
    } catch (err) {
        console.log(err.message)
    }
    console.log('server is running on port ' + process.env.PORT);
});
Enter fullscreen mode Exit fullscreen mode
  • Then create db.js file and setup the mongoDB
const mongoose = require('mongoose');
require('dotenv').config()

const connection = mongoose.connect(process.env.mongoUrl);

module.exports = {
    connection,
};
Enter fullscreen mode Exit fullscreen mode
  • In the above code we have process.env.mongoUrl, this code specifics the mongoDB connection string which was in .env environmental file.
mongoUrl = "mongodb+srv://<username>:<password>@cluster0.5hjxnse.mongodb.net/<table_name>?retryWrites=true&w=majority&appName=Cluster0"
PORT = 4000
Enter fullscreen mode Exit fullscreen mode
  • Don't forgot to add your current IP address in mongo atlas, while setup your DB, because mongoDB requires your system's current IP address

error when IP not added in mongo atlas

  • If you add your current IP address, then the error will be resolve.

error resolved, added IP in mongo atlas

  • So, yeah we connected our MongoDB in our NodeJS application. Now, lets test one API call to maske sure your endpoint are working.

I use tunderclient to test my API call in vscode.

  • Now go to any API testing tool like postman or tunderclient to make API call to our localhost.

tunderclient ui in vs code

So, that it our server is working fine. This server run on localhost with port number 4000
http://localhost:4000/

Happy Dev!

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more