forked from fineanmol/Hacktoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 30
/
anuj1
65 lines (56 loc) · 1.55 KB
/
anuj1
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
60
61
62
63
64
65
const express = require('express');
const { ObjectId } = require('mongodb');
const {connectToDb, getDb} = require('./db')
const app = express();
let db;
connectToDb((err) =>{
if(!err){
app.listen(3000,()=>{
console.log("app listening on post 3000")
})
db = getDb();
}
})
app.use(express.json());
app.get('/books',(req,res)=>{
let books = []
db.collection('books')
.find().sort({_id : 1})
.forEach((book)=> books.push(book))
.then(()=>{
res.status(200).json(books);
})
.catch(()=>{
console.log(err);
res.status(500).sendDate('Not found');
})
})
app.get('/books/:id',(req,res)=>{
if(ObjectId.isValid(req.params.id)){
db.collection('books')
.findOne({_id : ObjectId(req.params.id)})
.then((book) => res.status(200).json(book))
.catch((err)=>res.status(400).json("Not found"))
}
})
app.delete('/books/:id',(req,res)=>{
if(ObjectId.isValid(req.params.id)){
db.collection('books')
.delete({_id : ObjectId(req.params.id)})
.then((msg) => res.status(200).json(msg))
.catch((err)=>res.status(400).json("Not found"))
}
})
app.post('/books',(req,res)=>{
db.collection('books')
.insertOne(req.body)
.then((msg) => res.json(msg))
.catch((err) => res.json(err))
})
app.patch('/books/:id',(req,res)=>{
const update = req.body;
db.collection('books')
.updateOne({_id : ObjectId(req.params.id)},{$set : {update}})
.then((msg) => res.json(msg))
.catch((err) => res.json(err))
})