-
Notifications
You must be signed in to change notification settings - Fork 0
/
3(B) Create four API using Node.JS, ExpressJS and MongoDB for CURD
57 lines (57 loc) · 1.43 KB
/
3(B) Create four API using Node.JS, ExpressJS and MongoDB for CURD
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Package.json
{
"name": "ass2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.19.2",
"mongodb": "^6.5.0"
}
}
//index.js
const dbConnect = require('./mongodb')
const express = require('express');
const app = express();
app.use(express.json())
//get api
app.get('/getData' , async(req , res) => {
let result = await dbConnect();
result = await result.find().toArray();
res.send(result);
})
//post api
app.post('/insertData' , async(req , res) => {
let result = await dbConnect();
result =await result.insertOne(req.body);
res.send("Data Inserted Successfully")
})
//put api
app.put('/updataData/:name' , async(req , res) => {
let result = await dbConnect();
result = await result.updateOne({name:req.params.name} , {$set:req.body});
res.send("Data Updated Successfully")
})
//delete api
app.delete('/deleteData/:name' , async(req , res) => {
let result = await dbConnect();
result = await result.deleteOne({name:req.params.name})
res.send("Data Deleted Successfully");
})
app.listen(3000)
//mongodb.js
const {MongoClient} = require('mongodb');
const url = "mongodb://localhost:27017"
const database = 'student';
const client = new MongoClient(url);
const dbConnect = async() => {
const result = await client.connect();
const db = await result.db(database);
return db.collection('profile');
}
module.exports = dbConnect