-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
85 lines (73 loc) · 2.24 KB
/
app.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config();
const app = express();
const port = 5000;
//middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require("mongodb").ObjectId;
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.yorqu.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`;
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
client.connect((err) => {
const booksCollection = client.db("onlineBookStore").collection("books");
const ordersCollection = client.db("onlineBookStore").collection("orders");
app.post("/addBook", (req, res) => {
const book = req.body;
booksCollection.insertOne(book).then((result) => {
console.log(result.insertedCount);
res.send(result.insertedCount > 0);
});
});
app.get("/books", (req, res) => {
booksCollection.find().toArray((err, documents) => {
res.send(documents);
});
});
app.get("/orders", (req, res) => {
ordersCollection.find().toArray((err, documents) => {
res.send(documents);
});
});
app.get("/book/:key", (req, res) => {
//console.log(req.params.id);
booksCollection.find({ key: req.params.key }).toArray((err, documents) => {
res.send(documents[0]);
//console.log(err);
});
});
app.delete("/delete/:id", (req, res) => {
booksCollection
.deleteOne({ _id: ObjectId(req.params.id) })
.then((result) => {
console.log(result);
});
});
app.post("/booksByKeys", (req, res) => {
const bookKeys = req.body;
booksCollection
.find({ key: { $in: bookKeys } })
.toArray((err, documents) => {
res.send(documents);
});
});
app.post("/addOrder", (req, res) => {
const order = req.body;
ordersCollection.insertOne(order).then((result) => {
console.log(result);
res.send(result);
});
});
});
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(process.env.PORT || port, () => {
console.log(`Node app started at port ${port}`);
});