Connection between MongoDB and Node.js
This commit is contained in:
105
Week-05/Day_05/README.md
Normal file
105
Week-05/Day_05/README.md
Normal file
@@ -0,0 +1,105 @@
|
||||
# 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
|
||||
|
||||
```bash
|
||||
npm init -y
|
||||
npm install mongodb
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Connect to MongoDB
|
||||
|
||||
```js
|
||||
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
|
||||
|
||||
```js
|
||||
const db = client.db('studentDB');
|
||||
const collection = db.collection('students');
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Insert Data
|
||||
|
||||
```js
|
||||
await collection.insertOne({
|
||||
name: "Rahul",
|
||||
course: "MCA"
|
||||
});
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fetch Data
|
||||
|
||||
```js
|
||||
const data = await collection.find().toArray();
|
||||
console.log(data);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Update Data
|
||||
|
||||
```js
|
||||
await collection.updateOne(
|
||||
{ name: "Rahul" },
|
||||
{ $set: { course: "MBA" } }
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Delete Data
|
||||
|
||||
```js
|
||||
await collection.deleteOne({ name: "Rahul" });
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
project/
|
||||
│
|
||||
├── node_modules/
|
||||
├── app.js
|
||||
├── package.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Run the Application
|
||||
|
||||
```bash
|
||||
node app.js
|
||||
```
|
||||
Reference in New Issue
Block a user