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 Connect Mongodb Compass to Flask
Next article icon

How to Connect Node to a MongoDB Database ?

Last Updated : 27 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 environment to advanced techniques, ensuring you’re equipped to connect Node.js with MongoDB efficiently.

What is MongoDB and Mongoose?

MongoDB: A NoSQL database designed for handling large amounts of unstructured data. Unlike traditional relational databases that use tables with rows and columns to store data, MongoDB uses a flexible document-based model. Data is stored in collections and documents where each document is a JSON-like object

Mongoose: An Object Data Modeling (ODM) library for Node.js that simplifies working with MongoDB. It provides predefined methods for schema validation, database connection, and querying. It provides a higher-level abstraction over the native MongoDB driver, making it easier to define data structures and enforce validation rules.

Step-by-Step Guide to Connect Node.js to MongoDB

Connecting Node.js to MongoDB is essential for building scalable and efficient backend applications. This guide will walk you through the necessary steps to establish a seamless connection and interact with MongoDB using Mongoose.

Step 1: Install mongoose in your system using the below command.

Before you begin, ensure you have Node.js and npm installed on your system. To install Mongoose, run the following command in your terminal or command prompt:

npm install mongoose

Mongoose will allow us to interact with MongoDB using JavaScript in an easier, more efficient manner.

Step 2: Import Mongoose in Your Node.js Application

To connect a Node.js application to MongoDB, we have to use a library called Mongoose.  

const mongoose = require("mongoose");

Step 3: Establish a Connection to MongoDB

Use Mongoose’s connect() method to establish a connection with MongoDB. Here’s how to connect to a local MongoDB instance:

mongoose.connect("mongodb://localhost:27017/collectionName", {    useNewUrlParser: true,    useUnifiedTopology: true });
  • mongodb://localhost:27017/yourDatabaseName: Replace yourDatabaseName with the name of your MongoDB database.
  • useNewUrlParser and useUnifiedTopology: These options ensure that you are using the latest MongoDB connection logic and avoid deprecation warnings.

Step 4: Define the Schema

Schemas define the structure of the documents in your collection. They specify the types of data stored and can enforce rules like required fields and default values. Here’s an example of a simple schema for storing contact form submissions:

const contactSchema = new mongoose.Schema({   email: { type: String, required: true },   query: { type: String, required: true }, });
  • mongoose.Schema: Defines the structure of the MongoDB document.
  • required: true: Specifies that these fields must be provided when creating a document.

Step 5: Create a Model with the defined schema

Once you’ve defined the schema, the next step is to create a model. A model is a wrapper around the schema and allows you to interact with MongoDB collections (e.g., create, read, update, delete operations).

const Contact = mongoose.model("Contact", contactSchema); 

The model will automatically map to the contacts collection in MongoDB.

Step 6: Handling Form Submission and Storing Data

Let’s implement the functionality to store data submitted from a contact form in MongoDB. When a user submits the form, the data will be saved to the MongoDB database. Then, finally, we are able to store data in our document.

const express = require('express'); const app = express(); app.use(express.urlencoded({ extended: true }));  app.post('/contact', (req, res) => {   const contact = new Contact({     email: req.body.email,     query: req.body.query,   });    contact.save((err) => {     if (err) {       return res.status(500).send('Error saving data');     }     res.redirect('/thank-you');   }); });  app.listen(3000, () => {   console.log('Server running on port 3000'); }); 
  • Express: A minimal web application framework for Node.js used to handle HTTP requests. It simplifies routing and handling form data.
  • contact.save(): Saves the document to MongoDB. If successful, it redirects to a “Thank You” page.

Step 7: MongoDB CRUD Operations with Mongoose

After setting up the connection and model, it’s essential to understand how to perform basic CRUD (Create, Read, Update, Delete) operations with Mongoose.

1. Create: Insert a new document.

const newContact = new Contact({ email: "[email protected]", query: "How do I use MongoDB?" }); newContact.save();

2. Read: Retrieve documents from the collection.

Contact.find({}, (err, contacts) => {   if (err) throw err;   console.log(contacts); });

3. Update: Modify existing documents.

Contact.updateOne({ email: "[email protected]" }, { $set: { query: "New query" } }, (err) => {   if (err) throw err;   console.log("Document updated"); });

4. Delete: Remove documents from the collection.

Contact.deleteOne({ email: "[email protected]" }, (err) => {   if (err) throw err;   console.log("Document deleted"); });

Advanced Concepts for Connecting Node.js to MongoDB

1. Using MongoDB Atlas for Cloud Hosting

  • MongoDB Atlas is a fully-managed cloud database service. It simplifies MongoDB hosting with automated backups, scaling, and security.
  • To connect your Node.js application to MongoDB Atlas, simply replace the local connection string with the one provided by Atlas:
mongoose.connect("mongodb+srv://username:[email protected]/yourDatabase", { useNewUrlParser: true, useUnifiedTopology: true });

2. Mongoose Middleware (Hooks)

Mongoose allows you to define pre- and post- hooks to run certain functions before or after an operation like saving a document.

Example of pre-save hook:

contactSchema.pre('save', function(next) {   this.email = this.email.toLowerCase();   next(); });

3. Aggregation Framework in MongoDB

MongoDB’s aggregation framework allows you to process data records and return computed results. This is useful for tasks like filtering, sorting, and summarizing data.

Example aggregation to group contacts by their email domain:

Contact.aggregate([   { $group: { _id: { $substr: ["$email", 0, 5] }, count: { $sum: 1 } } } ]).exec((err, result) => {   if (err) throw err;   console.log(result); });

Best Practices for Connecting Node.js to MongoDB

  • Handle Errors: Always implement error handling to ensure your application doesn’t crash due to database connection or query issues.
  • Environment Variables: Store sensitive information such as database URIs, credentials, and secrets in environment variables using .env files.
  • Indexing: Use MongoDB indexing for faster querying, especially with large datasets.
  • Connection Pooling: Use Mongoose’s built-in connection pooling to manage multiple database connections efficiently.

Example: HTML Form for Contact Submission

Here’s an example of a simple contact form that interacts with the Node.js application:

<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta http-equiv="X-UA-Compatible"            content="IE=edge">     <meta name="viewport"            content="width=device-width,                     initial-scale=1.0">     <title>Document</title> </head>  <body>     <form action="/contact" method="post">         <input type="text"                 placeholder="Email"                 name="email">         <input type="text"                 placeholder="Query"                 name="query">         <button type="submit">             Submit         </button>     </form> </body>  </html>

Output

Conclusion

Connecting Node.js to MongoDB with Mongoose simplifies database interactions and offers powerful tools for working with MongoDB’s NoSQL architecture. By following this guide, we can easily integrate MongoDB into your Node.js applications and handle everything from basic CRUD operations to advanced features like aggregation and middleware. With its ease of use and flexibility, Mongoose helps streamline database management and improves productivity.



Next Article
How to Connect Mongodb Compass to Flask
author
devaadi
Improve
Article Tags :
  • Databases
  • MongoDB
  • Node.js
  • MongoDB
  • Mongoose
  • NodeJS-Questions

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 to a MongoDB Database Using the Node.js Driver ?
    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 b
    4 min read
  • How To Connect MongoDB Database in a Node.js Applications ?
    To connect MongoDB to a Node.js application, you can follow a simple process using the Mongoose library, which provides a flexible way to work with MongoDB. Mongoose acts as an Object Data Modeling (ODM) library, making it easier to structure and interact with MongoDB from Node.js. Prerequisites:Nod
    2 min read
  • How to Create a MongoDB Dump of Database
    MongoDB is a popular NoSQL database known for its flexibility, scalability, and ease of use. However, to protect our data from potential data loss or corruption, it’s critical to have a reliable MongoDB backup strategy in place. In this article, we will go through the process of creating a MongoDB d
    7 min read
  • How to Connect Mongodb Compass to Flask
    An effective GUI tool for managing and visualizing MongoDB data is MongoDB Compass. On the other hand, a well-liked Python web framework for creating web apps is called Flask. Integrating your MongoDB data into your Flask web application may benefit from connecting MongoDB Compass to Flask. Through
    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 Back Up and Restore a MongoDB Database?
    MongoDB is considered one of the classic examples of NoSQL systems. Its documents are made up of key-value pairs, which are the basic unit of data in MongoDB. Whether we're dealing with accidental data loss, hardware failures, or other unforeseen issues, having a solid backup and restoration plan ca
    5 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 Secure the MongoDB Database
    In today’s digital era, securing databases is more critical than ever, especially for organizations storing sensitive user and business data. MongoDB, a widely used NoSQL database, requires robust security measures to prevent unauthorized access, data breaches, and cyber threats. By default, MongoDB
    11 min read
  • How To Handle Global Connection of MongoDB in NodeJs?
    Handling a global connection to MongoDB in a Node.js application is important for efficient resource management and performance optimization. By maintaining a single connection to the MongoDB database, you avoid the overhead of repeatedly establishing and closing connections, which can be resource-i
    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