![]() |
VOOZH | about |
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.
Connecting Node.js to MongoDB is essential for building scalable and efficient backend applications.
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 mongooseMongoose will allow us to interact with MongoDB using JavaScript in an easier, more efficient manner.
To connect a Node.js application to MongoDB, we have to use a library called Mongoose.
const mongoose = require("mongoose");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
});
yourDatabaseName with the name of your MongoDB database.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 },
});
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.
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');
});
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: "test@example.com", 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: "test@example.com" }, { $set: { query: "New query" } }, (err) => {
if (err) throw err;
console.log("Document updated");
});
4. Delete: Remove documents from the collection.
Contact.deleteOne({ email: "test@example.com" }, (err) => {
if (err) throw err;
console.log("Document deleted");
});
mongoose.connect("mongodb+srv://username:password@cluster.mongodb.net/yourDatabase",
{ useNewUrlParser: true, useUnifiedTopology: true });
Mongoose allows you to define pre- and post- hooks to run certain functions before or after an operation like saving a document.
contactSchema.pre('save', function(next) {
this.email = this.email.toLowerCase();
next();
});
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.
Contact.aggregate([
{ $group: { _id: { $substr: ["$email", 0, 5] }, count: { $sum: 1 } } }
]).exec((err, result) => {
if (err) throw err;
console.log(result);
});
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