-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMongoDBCRUB.js
More file actions
75 lines (63 loc) · 1.67 KB
/
MongoDBCRUB.js
File metadata and controls
75 lines (63 loc) · 1.67 KB
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
69
70
71
72
73
74
75
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
mongoose.connect('mongodb://admin:MIFatq55127@node50164-netiya.proen.app.ruk-com.cloud:11523',
{ useNewUrlParser: true,
useUnifiedTopology: true,
}
);
const Book = mongoose.model('Book', {
id: Number,
title: String,
author: String,
});
const app = express();
app.use(bodyParser.json());
app.post("/books", async (req, res) => {
try {
const book = new Book(req.body);
book.id = (await Book.countDocuments()) + 1;
await book.save();
res.send(book);
} catch (error) {
res.status(500).send(error);
}
});
app.get("/books", async (req, res) => {
try {
const books = await Book.find();
res.send(books);
} catch (error) {
res.status(500).send(error);
}
});
app.get("/books/:id", async (req, res) => {
try {
const book = await Book.findOne(req.params.id);
res.send(book);
} catch (error){
res.status(500).send(error);
}
});
app.put("/books/:id", async (req, res) => {
try {
const book = await Book.findOneAndUpdate(req.params.id, req.body, {
new: true,
});
res.send(book);
} catch (error) {
res.status(500).send(error);
}
});
app.delete("/books/:id", async (req, res) => {
try {
const book = await Book.findOneAndDelete(req.params.id);
res.send(book);
} catch (error){
res.status(500).send(error);
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server started at http://localhost:${PORT}`)
});