-
Notifications
You must be signed in to change notification settings - Fork 0
/
21.js
59 lines (51 loc) · 1.52 KB
/
21.js
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
58
59
// Get Data from MongoDB
const express = require('express')
const app = express()
const {connectToDB} = require('./dbConnection')
app.use(express.json())
app.get('/',async(req,res)=>{
try {
const db = await connectToDB()
const collection = db.collection('users')
const users = await collection.find().toArray()
res.json(users)
} catch (error) {
console.error(error);
res.status(500).json({error: 'Internal Server Error'})
}
})
app.post('/users', async(req, res)=>{
try {
const data = req.body
const db = await connectToDB();
const collection = db.collection("users");
const insertData = await collection.insertOne(data)
console.log(`${insertData} Document Inserted`)
} catch (error) {
console.error(error)
}
})
app.put('/users/:firstName', async(req, res)=>{
try {
const db = await connectToDB();
const collection = db.collection("users");
const updateData = await collection.updateOne({firstName: req.params.firstName},{$set: req.body})
console.log(`${updateData} Document Updated`)
} catch (error) {
console.error(error)
}
})
app.delete('/users/:firstName', async(req, res)=>{
try {
const db = await connectToDB();
const collection = db.collection("users");
const fName = req.params.firstName
const deletedData = await collection.deleteOne({ firstName: fName });
console.log(`${deletedData} Document Deleted`);
} catch (error) {
console.error(error);
}
})
app.listen(3000, ()=>{
console.log("Server is listing on 3000")
})