How to Connect with Username/Password to MongoDB using native node.js Driver?
Last Updated :
24 Jul, 2024
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 with username/password to Mongodb using native node.js driver.
Prerequisites
Steps to Connect with Username/Password to MongoDB using native node.js Driver
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 the required packages
Then install the required package using npm.
npm install express mongodb ejs nodemon
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.
Home pageStep 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.
Cluster CreationStep 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.
Username and PasswordStep 7: Choose a connection method
Once you have done all the steps, select the connection method as the first option (“Drivers”).
Choose a connection method as DriversStep 7: Copy the connection string
Now, you have to copy the string and paste it into your project. YOu have to replace the <username> and <password> to your actual username and password.
Then copy the connection string as shown below:
Copy the URL and paste your username and passwordStep 7: Create a Database user
You have to click on "Database Access" and it will leads you to the page where you can create a new user(if you have not already one). you can give them any access according to yourself. Then replace the <username> and <password> to your actual username and password.
Project Structure:
Folder structureUpdated dependencies:
"dependencies": {
"ejs": "^3.1.10",
"express": "^4.19.2",
"mongo": "^0.1.0",
"mongodb": "^6.8.0",
"nodemon": "^3.1.4"
}
Example: Below is the code example of how to Connect with username/password to mongodb using native node.js driver
HTML
<!-- index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Task Management</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<h1>Task Management</h1>
<a href="/add-task">Add New Task</a>
<ul>
<% tasks.forEach(task=> { %>
<li><strong>
<%= task.name %>:
</strong>
<%= task.description %>
</li>
<% }) %>
</ul>
</body>
</html>
HTML
<!-- addTask.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1.0">
<title>Add Task</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>Add a New Task</h1>
<form action="/add-task" method="POST">
<label for="name">Task Name:</label>
<input type="text" id="name" name="name" required>
<label for="description">Task Description:</label>
<textarea id="description" name="description" required></textarea>
<button type="submit">Add Task</button>
</form>
</body>
</html>
CSS
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
color: #333;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
}
h1 {
margin-bottom: 20px;
}
ul {
list-style-type: none;
padding: 0;
}
li {
background: #fff;
margin: 5px 0;
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
form {
display: flex;
flex-direction: column;
}
label {
margin: 5px 0;
}
input,
textarea,
button {
margin: 5px 0;
padding: 10px;
border-radius: 5px;
border: 1px solid #ccc;
}
button {
background-color: #28a745;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
JavaScript
// server.js....
const express = require('express');
const path = require('path');
const { getTasks, addTask } = require('./task');
const app = express();
const port = 3000;
// Middleware
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
// Routes
app.get('/', async (req, res) => {
try {
const tasks = await getTasks();
res.render('index', { tasks });
} catch (error) {
res.status(500).send(error);
}
});
app.get('/add-task', (req, res) => {
res.render('addTask');
});
app.post('/add-task', async (req, res) => {
const { name, description } = req.body;
try {
await addTask({ name, description });
res.redirect('/');
} catch (error) {
res.status(500).send(error);
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
JavaScript
// db.js
const { MongoClient } = require('mongodb');
const uri =
'YOUR_URL_OF_MONGO_DRIVE';
const client = new MongoClient(uri, {
});
const connectDB = async () => {
try {
await client.connect();
console.log('Connected to database');
return client.db();
} catch (error) {
console.error('Error connecting to database', error);
process.exit(1);
}
};
module.exports = connectDB;
JavaScript
// task.js
const { MongoClient } = require('mongodb');
const connectDB = require('./db');
let db;
(async () => {
db = await connectDB();
})();
const getTasks = async () => {
return await db.collection('tasks').find().toArray();
};
const addTask = async (task) => {
await db.collection('tasks').insertOne(task);
};
module.exports = { getTasks, addTask };
Step to run the project
nodemon server.js
Output:
Output for task add.Database Output:
Database Output
Similar Reads
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 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 rename the collection name 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 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 mongodb Server with Node.js ?
mongodb.connect() method is the method of the MongoDB module of the Node.js which is used to connect the database with our Node.js Application. This is an asynchronous method of the MongoDB module. Syntax: mongodb.connect(path,callbackfunction)Parameters: This method accept two parameters as mention
2 min read
How to count total number of unique documents in MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Insta
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
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
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 Perform a Find Operation With Sorting In MongoDB Using Node.js?
Performing a find operation with sorting in MongoDB using Node.js is a common task for developers working with databases. This guide will walk you through the process step-by-step, including setting up a MongoDB database, connecting to it using Node.js, performing a find operation, and sorting the r
3 min read