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 NodeJS
Step 1: Create a NodeJS App: First create a NodeJS app using the following command:
npm init -y
cd foldername
Step 2: Install required packages: Second, you need to install the required package using NPM
npm install express ejs
Step 3: Install Mongoose: Then install Mongoose using npm
npm install mongoose
Step 4: Require Mongoose: After that in your NodeJS application, you need to require Mongoose.
const mongoose = require('mongoose');
Step 5: Call the connect method : Then you need to call the mongoose connect mothod to connect it.
// Here you can use the database name as your need
const url = 'mongodb://localhost:27017/mydatabase';
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);
}
};
Step 6: 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: String,
age: Number
});
//Here you can add some more data as your need.
Project Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"ejs": "^3.1.10",
"express": "^4.19.2",
"mongoose": "^8.3.4"
}
Example: Below is the code example of how to connect NodeJS to a mongodb database.
<!-- views/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="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;
}
</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" required>
<label for="age">Age:</label>
<input type="number" id="age" name="age" required>
<button type="submit">Submit</button>
</form>
</div>
<script>
function validateForm() {
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
if (name === "" || age === "") {
alert("Please enter your name and age.");
return false;
}
return true;
}
</script>
</body>
</html>
// server.js code ....
const express = require("express");
const mongoose = require("mongoose");
const port = 3000;
const connectDB = require("./database/db.js");
const User = require("./model/model.js");
const app = express();
connectDB();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.set('views', './views');
// GET route for the home page
app.get("/", (req, res) => {
res.render("index");
});
app.post("/user", async (req, res) => {
try {
// Create a new user document
const newUser = new User({
name: req.body.name,
age: req.body.age
});
// Save the user to the database
await newUser.save();
res.send("User data saved successfully!");
} catch (err) {
console.error("Error saving user data:", err);
res.status(500).send("Error saving user data");
}
});
app.listen(port, (err) => {
if (err) {
console.log(err);
} else {
console.log(`Server is started at port no ${port}`);
}
});
// databse/db.js code ...
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/mydatabase';
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;
//model/model.js code..
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
age: Number
});
const Userdb = mongoose.model('User', userSchema);
module.exports = Userdb;
To run the code wite in the command prompt.
node server.js
And open a new tab of your browser and type the following command to show the output.
http://localhost:3000/
Output:
Database Output:
Contact Us