Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to create new Mongodb database using Node.js ?
Next article icon

How to Connect to a MongoDB Database Using the Node.js Driver ?

Last Updated : 08 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB is a popular, open-source, NoSQL (non-relational) database that provides high performance, high availability, and easy scalability. Unlike traditional relational databases, MongoDB stores a JSON-like format called BSON (Binary JSON).

In this article, we connect the MongoDB database to your backend application built by Node.js.

Setup for Database Connection

  • Installation : For connecting MongoDB to the backend, you have to install MongoDB on your local system or you can also create an account on MongoDB atlas and get your MongoDB credentials like URL.
  • Node.js Driver: The next step is to install the Node.js to your local system ( if it is not available)
  • Module: Installing the module ( MongoDB, Mongoose ) to connect the database.
  • Connect to MongoDB: This step establishes a connection to the MongoDB server.

Below mentioned are 2 approaches to connect database in the application.

Table of Content

  • Using MongoDB
  • Using Mongoose

Using MongoDB

Install MongoDB module. Establish a connection to the MongoDB database by creating an instance of the MongoClient class and providing the MongoDB connection URI.

Steps to Create Application

Step 1. Project Structure : Make a folder named 'mongodb-connection' and navigate to it using this command.

mkdir mongodb-connection  cd mongodb-connection

Step 2. Install Module : Install required module like mongodb , express.

npm i mongodb express dotenv

Updated dependencies in package.json file

"dependencies": {      "dotenv": "^16.4.5",      "express": "^4.19.2",      "mongodb": "^6.6.0"    }

Project Structure:

mongodb-connection
Project Structure

Example: This example demonstrates connection to database using the MongoDB.

JavaScript
// server.js   const { MongoClient } = require('mongodb');  // Connect to the MongoDB server async function connectToMongoDB() {     // Create a new MongoClient     const client = new MongoClient(process.env.DB_URI);     try {         await client.connect();         console.log('Connected to MongoDB');         return client.db();     } catch (error) {         console.error('Error connecting to MongoDB:', error);         throw error;     } }  module.exports = connectToMongoDB;  
JavaScript
// app.js   const express = require('express') const app = express(); const dotenv = require('dotenv') const connectToMongoDB = require('./server')  dotenv.config()  const PORT = process.env.PORT || 5000  // Function to insert an item async function insertItem(itemData) {     try {         const db = await connectToMongoDB();         const collection = db.collection('items');         const result = await collection.insertOne(itemData);         console.log('Item inserted : ', result);         return result;     } catch (error) {         console.error('Error inserting item:', error);         throw error;     } }  // Example usage const newItemData = { name: 'Example Item',                        description: 'This is an example item',                        quantity: 3 }; insertItem(newItemData);  app.listen(PORT, () => {     console.log(`Server is running on PORT ${PORT}`) }) 

Output:

mongodb-output
Mongo DB Output

Using Mongoose

Installing Mongoose in your Node.js project using npm. Connect your MongoDB database by providing the MongoDB connection URI. Mongoose.connect method.

Steps to Create Application and Install Required Modules

Step 1. Project Structure : Make a folder named 'mongoose-connection' and navigate to it using this command.

mkdir mongoose-connection  cd mongoose-connection

Step 2. Install Module : Install required module like mongoose , express.

npm i mongoose express dotenv

Updated dependencies in package.json file

"dependencies": {      "express": "^4.19.2",      "mongoose": "^8.3.3",  }

Example: This example demonstrates connection to database using Mongoose.

JavaScript
// server.js  const mongoose = require('mongoose') const DB_URI = 'xxx-xxx'  const dbConnection = () => {     mongoose.connect(DB_URI);     console.log('Database is successfully connected!') }  // Define a schema const itemSchema = new mongoose.Schema({     name: String,     description: String,     quantity: Number });  // Define a model const Item = mongoose.model('Item', itemSchema)  module.exports = {     Item, dbConnection } 
JavaScript
// app.js   const express = require('express'); const app = express(); const { Item, dbConnection } = require('./server')  const PORT = process.env.PORT || 8000; //  app.use(express.json()) dbConnection();   async function Inserting() {     // Example of creating a new document     const newItem = new Item({ name: 'Example Item',                               description: 'This is an example item',                               quantity: 3 });     await newItem.save()     console.log(newItem) }  Inserting(); app.listen(PORT, () => {     console.log(`Server is running on ${PORT}`) }) 

Output:

mongoose-output
Mongoose Output

MongoDB Output:

mongo-database-output
Output at Mongo Database



Next Article
How to create new Mongodb database using Node.js ?

R

renuxqmuo
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • MongoDB

Similar Reads

  • How to Connect to a MongoDB Database Using Node.js
    MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. To connect to a MongoDB database using NodeJS we use the MongoDB library "mongoose". Steps to Connect to a MongoDB Database Using NodeJSStep 1: Create a NodeJS App: First create a NodeJ
    4 min read
  • How to Connect Node to a MongoDB Database ?
    Connecting Node.js to MongoDB is a common task for backend developers working with NoSQL databases. MongoDB is a powerful, flexible, and scalable database that stores data in a JSON-like format. In this step-by-step guide, we'll walk through the entire process from setting up your development enviro
    6 min read
  • How to drop database of MongoDB using Node.js ?
    MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
    2 min read
  • How to drop all databases present in MongoDb using Node.js ?
    MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
    2 min read
  • How to create new Mongodb database using Node.js ?
    mongodb module: This Module is used to performing CRUD(Create Read Update Read) Operations in MongoDb using Node.js. We cannot make a database only. We have to make a new Collection to see the database. The connect() method is used for connecting the MongoDb server with the Node.js project. Please r
    1 min read
  • How to Connect SQLite3 Database using Node.js ?
    Connecting SQLite3 database with Node.js involves a few straightforward steps to set up and interact with the database. SQLite is a self-contained, serverless, zero-configuration, transactional SQL database engine, making it ideal for small to medium-sized applications. Here’s how you can connect an
    2 min read
  • How to Seed a MongoDB Database Using Docker Compose
    Seeding a MongoDB database is a common task in many development and testing scenarios. It involves populating the database with initial data to ensure consistent and predictable behavior during the application development and testing phases. Docker Compose is a powerful tool that simplifies the proc
    4 min read
  • How to Connect Node.js To MongoDB Atlas Using Mongoose?
    MongoDB Atlas is a cloud-based database service that offers robust features and scalability for managing our data. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. And also we use the Ejs for our front end to render the simple HTML form. In this tutoria
    6 min read
  • How to Connect to a MySQL Database Using the mysql2 Package in Node.js?
    We will explore how to connect the Node.js application to a MySQL database using the mysql2 package. MySQL can be widely used as a relational database and mysql2 provides fast, secure, and easy access to MySQL servers, it can allow you to handle database queries efficiently in Node.js applications.
    6 min read
  • How to sort collection of MongoDB Database in descending order using Node.js ?
    MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences