MongoDB with Node.js
Introduction
In this task, we connect MongoDB with Node.js to perform database operations using JavaScript. This allows building dynamic backend applications.
Install Required Package
npm init -y
npm install mongodb
Connect to MongoDB
const { MongoClient } = require('mongodb');
const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);
async function connectDB() {
try {
await client.connect();
console.log("Connected to MongoDB");
} catch (error) {
console.error(error);
}
}
connectDB();
Access Database and Collection
const db = client.db('studentDB');
const collection = db.collection('students');
Insert Data
await collection.insertOne({
name: "Rahul",
course: "MCA"
});
Fetch Data
const data = await collection.find().toArray();
console.log(data);
Update Data
await collection.updateOne(
{ name: "Rahul" },
{ $set: { course: "MBA" } }
);
Delete Data
await collection.deleteOne({ name: "Rahul" });
Project Structure
project/
│
├── node_modules/
├── app.js
├── package.json
Run the Application
node app.js