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:
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
Next article icon

How to Connect Node.js To MongoDB Atlas Using Mongoose?

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

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 tutorial, we will go through the process of how to connect Node.js to MongoDB atlas using Mongoose.

Prerequisites:

  • NPM & NodeJS
  • MongoDB

Steps to connect Node.js to MongoDB Atlas using Mongooose

Step 1: Create a New Directory

First create a new directory for your project and navigate into it.

mkdir Your_folder_name
cd Your_folder_name

Step 2: Initialize a New Node.js Project

After that, you have to Initialize a new node project using npm.

npm init -y

Step 3: Install required packages

Then install the required package using npm.

npm install express mongoose ejs dotenv

Step 4: Register to the MongoDB atlas

After that, you need to register to the MongoDB atlas to store the data in a MongoDB Atlas. Then you can see the page like the image below.


compressed_atlas-homepage
Home page

Step 5: Create a Cluster

Then You need to create a cluster for that click on the "create" button and choose the free tier (M0). Click on the "Create Deployment" button.

compressed_Screenshot-_471_
Cluster Creation

Step 6: Create a database user

A username and password can be autogenerated, but you can change those and provide a good username and a password, avoid any special characters (#!@$%^_&) in your password otherwise you can not connect it with the database. Once you are done, click on the 'Create Database User' button.

Screenshot-_471_-(1)
Username and Password

Step 7: Choose a connection method

Once you have done all the steps, select the connection method as the first option (“Drivers”).

Screenshot-_471_-(2)
Choose a connection method as Drivers

Then copy the connection string as shown below.

Screenshot-_473_
Copy the String


Step 8: Create a .env file

After that create a .env file in your project root directory to hide the sensitive details and put your connection string in there.

MONGODB_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>?retryWrites=true&w=majority

//
Here put your username , password and a database name...
//

Step 9: Require Mongoose

After that in your NodeJS application, you need to require Mongoose.

const mongoose = require('mongoose');

Step 10: Call the connect method

Then you need to call the Mongoose connect method to connect it.

const mongoose = require('mongoose');
require('dotenv').config();

const url = process.env.MONGODB_URI;
const connectDB = async () => {
try {
await mongoose.connect(url, {

});
console.log('Database is connected');
} catch (err) {
console.error('Error connecting to the database:', err);
process.exit(1);
}
};

module.exports = connectDB;

Step 11: Then Define a schema

A schema is a structure, that gives information about how the data is being stored in a collection.

const userSchema = new Schema({
name: {
type: String,
required: true,
},
email:{
type:String,
required:true,
},
mobile:{
type: Number,
required: true,
},
age: {
type: Number,
required: true,
},
});

//Here you can add some more data as your need.

Project Structure:

Screenshot-_475_
Folder structure

The Updated dependencies in package.json file:

"dependencies": {
"dotenv": "^16.4.5",
"ejs": "^3.1.10",
"express": "^4.19.2",
"mongoose": "^8.4.0"
}

Example: Below is the code example of how to Connect Node.js To MongoDB Atlas Using Mongoose

HTML
<!-- view/index.ejs !-->  <!DOCTYPE html> <html lang="en"> <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Home Page</title>     <style>         body {             font-family: Arial, sans-serif;             background-color: #f9f9f9;             margin: 0;             padding: 0;             display: flex;             justify-content: center;             align-items: center;             height: 100vh;         }          .container {             max-width: 400px;             padding: 20px;             background-color: #fff;             border-radius: 8px;             box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);         }          h1 {             color: #333;             text-align: center;             margin-bottom: 20px;         }          p {             color: #666;             text-align: center;             margin-bottom: 20px;         }          form {             text-align: center;         }          label {             display: block;             margin-bottom: 10px;             color: #333;         }          input[type="text"],         input[type="email"],         input[type="tel"],         input[type="number"],         button {             width: 100%;             padding: 10px;             margin-bottom: 15px;             border: 1px solid #ccc;             border-radius: 5px;             box-sizing: border-box;         }          button {             background-color: #007bff;             color: #fff;             cursor: pointer;         }          button:hover {             background-color: #0056b3;         }          .message {             color: green;             text-align: center;             margin-bottom: 20px;         }          .error {             color: red;             text-align: center;             margin-bottom: 20px;         }     </style> </head> <body>     <div class="container">         <h1>Welcome to our website!</h1>         <p>This is a simple form to save user data to the database.</p>         <form id="userForm" action="/user" method="post" onsubmit="return validateForm()">             <label for="name">Name:</label>             <input type="text" id="name" name="name" >             <label for="email">Email Id:</label>             <input type="email" id="email" name="email" >             <label for="mobile">Mobile No:</label>             <input type="tel" id="mobile" name="mobile" pattern="[0-9]{10}">             <label for="age">Age:</label>             <input type="number" id="age" name="age" >             <button type="submit">Submit</button>         </form>         <% if (message) { %>             <p class="message"><%= message %></p>         <% } else if (error) { %>             <p class="error"><%= error %></p>         <% } %>     </div>      <script>         function validateForm() {             var name = document.getElementById("name").value;             var email = document.getElementById("email").value;             var mobile = document.getElementById("mobile").value;             var age = document.getElementById("age").value;              if (name === "" || email === "" || mobile === "" || age === "") {                 alert("Please fill out all fields.");                 return false;             }              if (!/^[0-9]{10}$/.test(mobile)) {                 alert("Please enter a valid 10-digit mobile number.");                 return false;             }              return true;         }     </script> </body> </html> 
JavaScript
//server.js  const express = require('express'); const connectDB = require('./database/db'); const userRoutes = require('./routes/userRoutes');  const app = express(); const port = 3000;  // Connect to the database connectDB();  app.use(express.json()); app.use(express.urlencoded({ extended: true }));  // Set the view engine to EJS app.set('view engine', 'ejs'); app.set('views', './views');  // Routes app.use('/', userRoutes);  // Start the server app.listen(port, (err) => {   if (err) {     console.log(err);   } else {     console.log(`Server is started at port ${port}`);   } }); 
JavaScript
// databse/db.js  const mongoose = require('mongoose'); require('dotenv').config();  const url = process.env.MONGODB_URI; const connectDB = async () => {     try {         await mongoose.connect(url, {                     });         console.log('Database is connected');     } catch (err) {         console.error('Error connecting to the database:', err);         process.exit(1);     } };  module.exports = connectDB; 
JavaScript
//model/model.js  const mongoose = require('mongoose'); const Schema = mongoose.Schema;  const userSchema = new Schema({   name: {     type: String,     required: true,   },   email:{     type:String,     required:true,   },   mobile:{     type: Number,     required: true,   },   age: {     type: Number,     required: true,   }, });  const User = mongoose.model('User', userSchema);  module.exports = User; 
JavaScript
// routes/userRoutes.js  const express = require('express'); const User = require('../model/model'); const router = express.Router();  // GET route for the home page router.get('/', async (req, res) => {   try {     const users = await User.find();     res.render('index', { message: null, error: null, users });   } catch (err) {     console.error('Error fetching user data:', err);     res.status(500).render('index', { error: 'Error fetching user data', users: [] });   } });  // POST route for adding a user router.post('/user', async (req, res) => {   try {     const newUser = new User({       name: req.body.name,       email: req.body.email,       mobile: req.body.mobile,       age: req.body.age,     });     await newUser.save();     res.render('index', { message: 'User data saved successfully!', error: null, users: await User.find() });   } catch (err) {     console.error('Error saving user data:', err);     res.status(500).render('index', { error: 'Error saving user data', message: null, users: [] });   } });   module.exports = router; 

Output:

Database Output:

compressed_Screenshot-_477_
Output

Next Article
Node.js CRUD Operations Using Mongoose and MongoDB Atlas
author
skaftafh
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • MongoDB

Similar Reads

  • How to Connect to MongoDB Atlas Using Shell?
    MongoDB is a highly scalable NoSQL database, renowned for its ability to manage vast amounts of complex and unstructured data. Unlike traditional databases that use a tabular format, MongoDB employs a document-oriented approach, storing data in a flexible, JSON-like format. This makes MongoDB highly
    5 min read
  • 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 Use MongoDB and Mongoose with Node.js ?
    MongoDB is a popular NoSQL database that offers flexibility and scalability, making it an excellent choice for modern applications. Mongoose, a powerful ODM (Object Data Modeling) library, simplifies the interaction between MongoDB and Node.js by providing a schema-based solution for data validation
    6 min read
  • Node.js CRUD Operations Using Mongoose and MongoDB Atlas
    CRUD (Create, Read, Update, Delete) operations are fundamental in web applications for managing data. Mongoose simplifies interaction with MongoDB, offering a schema-based approach to model data efficiently. MongoDB Atlas is a fully managed cloud database that simplifies the process of setting up, m
    8 min read
  • How to Get Data from MongoDB using Node.js?
    One can create a simple Node.js application that allows us to get data to a MongoDB database. Here we will use Express.js for the server framework and Mongoose for interacting with MongoDB. Also, we use the EJS for our front end to render the simple HTML form and a table to show the data. Prerequisi
    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
  • Connect MongoDB with Node App using MongooseJS
    The process of integrating MongoDB, a NoSQL database, with a Node.js application using MongooseJS, a MongoDB object modelling tool designed to work in an asynchronous environment. Prerequisites:NodejsnpmMongoDBMongooseJSSteps to connect MongoDB with Node AppFollowing are the steps to connect MongoDB
    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 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 create new Collection 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 for
    1 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