Last Updated : 01 Aug, 2024
Summarize
Comments
Improve
To connect node to a MongoDB database we can use mongoose library from npm, It is an Object Data Modeling Library that provides predefined methods for database connection, creating schema and models.
MongoDB is a NoSQL database used to store large amounts of data without any traditional relational database table. Instead of rows & columns, MongoDB used collections & documents to store data. A collections consist of a set of documents & a document consists of key-value pairs which are the basic unit of data in MongoDB.
Steps to Connect Node to a MongoDB Database
Step 1: Install mongoose in your system using the below command.
npm install mongoose
Step 2: Import the mongoose library
To connect a Node.js application to MongoDB, we have to use a library called Mongoose.
const mongoose = require("mongoose");
Step 3: Use the Mongoose connect method to establish the connection
After that, we have to call the connect method of Mongoose
mongoose.connect("mongodb://localhost:27017/collectionName", {
useNewUrlParser: true,
useUnifiedTopology: true
});
Then we have to define a schema. A schema is a structure, that gives information about how the data is being stored in a collection.
Step 4: Define the Schema
Example: Suppose we want to store information from a contact form of a website.
const contactSchema = {
email: String,
query: String,
};
Then we have to create a model using that schema which is then used to store data in a document as objects.
Step 5: Create a Model with the defined schema
const Contact = mongoose.model("Contact", contactSchema);
Then, finally, we are able to store data in our document.
app.post("/contact", function (req, res) {
const contact = new Contact({
email: req.body.email,
query: req.body.query,
});
contact.save(function (err) {
if (err) {
res.redirect("/error");
} else {
res.redirect("/thank-you");
}
});
});
Example: Below is the code example of how to connect node.js to a mongodb database.
<!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>
const express = require("express");const ejs = require("ejs");const mongoose = require("mongoose");const bodyParser = require("body-parser");mongoose.connect("mongodb://localhost:27017/newCollection", { useNewUrlParser: true, useUnifiedTopology: true });const contactSchema = { email: String, query: String,};const Contact = mongoose.model("Contact", contactSchema);const app = express();app.set("view engine", "ejs");app.use(bodyParser.urlencoded({ extended: true}));app.use(express.static(__dirname + '/public'));app.get("/contact", function (req, res) { res.render("contact"); });app.post("/contact", function (req, res) { console.log(req.body.email); const contact = new Contact({ email: req.body.email, query: req.body.query, }); contact.save(function (err) { if (err) { throw err; } else { res.render("contact"); } }); });app.listen(3000, function () { console.log("App is running on Port 3000"); });
Output: