Integrating Node.js with MongoDB is a popular choice for developers building modern web applications due to its ease of use, scalability, and flexibility. MongoDB, a NoSQL database, pairs well with JavaScript-based Node.js, creating a powerful combination for managing and interacting with databases. In this blog, we will walk through the process of inserting and reading data from MongoDB using Node.js, explaining the code step-by-step.
Why Use MongoDB with Node.js?
Node.js is widely used for server-side applications due to its non-blocking I/O model and fast performance. MongoDB, being a document-based NoSQL database, stores data in JSON-like format (BSON). Using MongoDB with Node.js simplifies data interaction since JavaScript objects are natively supported, allowing seamless data exchange.
Some of the advantages of integrating MongoDB with Node.js include:
- Scalability: Easily scale both database and application based on load.
- Flexibility: NoSQL schema allows flexible and dynamic data structures.
- JSON Format: MongoDB stores data as JSON-like documents, which aligns with JavaScript objects used in Node.js.
Now let’s dive into the practical implementation where we insert and read data from MongoDB using Node.js.
Setting Up MongoDB and Node.js
Before we begin, ensure you have MongoDB installed and running on your machine, and Node.js set up.
- Install MongoDB: Download MongoDB from here.
- Install Node.js: Download and install Node.js from here.
- Install MongoDB Driver for Node.js: To interact with MongoDB from Node.js, install the
mongodb
package by running:
npm install mongodb@4.8
Once everything is set up, we can move forward with writing the code.
Code Explanation: Inserting and Reading Data
Here’s the full code for integrating Node.js with MongoDB:
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
async function ConnMongodb() {
const database = client.db("demo2-db");
const students = database.collection("student");
const mydoc = {
name: "Harsh",
phone: 11675,
marks: 50,
remarks: "nice"
};
const query = { name: "Harsh" };
const option = { projection: { _id: 0, name: 1, phone: 1 } };
const insertOut = await students.insertOne(mydoc);
const stdata = await students.findOne(query, option);
console.log(stdata);
await client.close();
}
ConnMongodb();
Let’s break this code down step-by-step to understand how it works:
1. Import the MongoDB Client:
const { MongoClient } = require("mongodb");
- We import
MongoClient
from themongodb
package. This is the primary client interface that will allow us to interact with our MongoDB server. - The
MongoClient
is the entry point for connecting to the MongoDB database.
2. Define the URI for MongoDB Connection:
const uri = "mongodb://127.0.0.1:27017";
- We define the URI of the MongoDB server that we will connect to.
"mongodb://127.0.0.1:27017"
refers to a MongoDB server running locally on your machine at port27017
, which is the default port for MongoDB.
3. Create the MongoDB Client:
const client = new MongoClient(uri);
- The
MongoClient
instance is created by passing the URI. - This client is responsible for establishing the connection with the MongoDB server and managing interactions with the database.
4. Connect to MongoDB and Select the Database and Collection:
const database = client.db("demo2-db");
const students = database.collection("student");
- We use the
client.db()
method to connect to a specific database. In this case, we are connecting to the database nameddemo2-db
. - The
database.collection()
method selects a collection within the database. In this case, we are working with thestudent
collection. - If the database or collection doesn’t exist, MongoDB will create it automatically when the first record is inserted.
5. Prepare the Document to Insert:
const mydoc = {
name: "Harsh",
phone: 11675,
marks: 50,
remarks: "nice"
};
- We define a document (
mydoc
) which is an object containing the details of a student:name
,phone
,marks
, andremarks
. - This document will later be inserted into the
student
collection.
6. Insert the Document into the Collection:
const insertOut = await students.insertOne(mydoc);
insertOne()
is used to insert a single document into the collection.- In this case, we insert
mydoc
into thestudent
collection. - The
await
keyword ensures that the program waits for the insertion to complete before moving on to the next step.
7. Query the Data:
const query = { name: "Harsh" };
const option = { projection: { _id: 0, name: 1, phone: 1 } };
- We create a query object to find a document with the name
Harsh
. - The
projection
option specifies which fields to include or exclude in the result. In this case, we are excluding the_id
field (by setting it to 0) and including only thename
andphone
fields (by setting them to 1).
8. Retrieve the Data Using `findOne()`:
const stdata = await students.findOne(query, option);
console.log(stdata);
- We use
findOne()
to search for the document that matches thequery
(name: "Harsh"). - The
projection
options ensure that the_id
field is excluded from the result. - Once the document is found, we log it to the console, which will display:
9. Close the MongoDB Connection:
await client.close();
- Finally, we close the connection to the MongoDB server using
client.close()
. Always close the connection when the operations are done to free up resources.
Conclusion
In this blog, we explored how to integrate Node.js with MongoDB and perform basic operations such as inserting and reading data. By breaking down each line of code, we saw how easy it is to interact with MongoDB using the official mongodb
package for Node.js. This simple setup is powerful for building dynamic and scalable applications.