How to connect MongoDB database in a Node.js Applications ?
Node.js is a built-in JavaScript Chrome platform to easily build faster and more flexible network applications. Node.js uses an event-driven, uninterrupted I / O model that makes it easy and efficient, suitable for real-time applications that use data that works on all distributed devices.
Node.js is an open-source, cross-platform working environment for server-side development and communication applications. Node.js applications are JavaScript enabled and can run during Node.js running time on OS X, Microsoft Windows, and Linux.
Node.js also provides a rich library of various JavaScript modules that facilitate the development of web applications using Node.js on a large scale.
Approach:-
- First, initialize the node.js project in the particular folder in your machine.
- install the node modules in the project folder
- After this create a connection to the database
Step 1: Create a NodeJS Project and initialize it using the following command:
npm init
Step 2: Install the node modules using the following command:
npm i express mongodb mongoose cors
File Structure: Our file structure will look like the following:

project folder structure
index.js
// To connect with your mongoDB database const mongoose = require( "mongoose" ); // Connecting to database mongoose.connect( { dbName: "yourDB-name" , useNewUrlParser: true , useUnifiedTopology: true , }, (err) => err ? console.log(err) : console.log( "Connected to yourDB-name database" ) ); const express = require( "express" ); const app = express(); const cors = require( "cors" ); console.log( "App listen at port 5000" ); |
Run index.js file using below command:
nodemon index.js

Output on console
Please Login to comment...