-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
68 lines (63 loc) · 1.99 KB
/
server.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
60
61
62
63
64
65
66
67
68
const mongoose = require('mongoose');
const express = require('express');
const Book = require('./models/booksmodels');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.send('Hello World!');
})
app.post('/addbook', async (req, res) => {
try{
const book =await Book.create(req.body)
res.status(201).json(book)
}catch(err){
console.log(err);
res.status(400).json({message:'Something went wrong'});
}
});
app.get('/getbooks', async (req, res) => {
try{
const books = await Book.find();
res.status(200).json(books);
} catch(err){
console.log(err);
res.status(400).json({message:'Something went wrong'});
}
});
app.delete('/deletebook/:id', async (req, res) => {
try{
const book = await Book.findByIdAndDelete(req.params.id);
if(!book){
res.status(404).json({message:'Book not found ${id}'});
}
res.status(200).json(book);
}catch(err){
console.log(err);
res.status(400).json({message:'Something went wrong'});
}
});
app.put('/updatebook/:id', async (req, res) => {
try{
const book = await Book.findByIdAndUpdate(req.params.id, req.body);
if(!book){
res.status(404).json({message:'Book not found ${id}'});
}
const updatebook=await Book.findById(req.params.id);
res.status(200).json(updatebook);
}catch(err){
console.log(err);
res.status(400).json({message:'Something went wrong'});
}
});
mongoose.set("strictQuery", false);
mongoose.connect('mongodb://localhost:27017/Ebook_database', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log('connected to local MongoDB');
app.listen(3001, () => {
console.log("Node API app is running on port 3001");
});
})
.catch((error) => {
console.log(error);
});