-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
62 lines (52 loc) · 1.4 KB
/
app.js
File metadata and controls
62 lines (52 loc) · 1.4 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
const express = require("express");
const dbConnect = require("./db");
const Book = require("./Book.model");
const app = express();
//Enviroment Variables
require("dotenv").config();
const DB_URI = process.env.URI;
//Databse connect function
dbConnect(DB_URI);
//Routes
app.get("/list", async (req, res) => {
try {
let match = {};
let page = parseInt(req.query.page) || 1;
let docsPerPage = 2;
let skip = docsPerPage * (page - 1);
let limit = docsPerPage;
if (req.query.keyword) {
match.$or = [
{ author: new RegExp(req.query.keyword, "i") },
{ title: new RegExp(req.query.keyword, "i") },
];
}
if (req.query.year) {
match.year = parseInt(req.query.year);
}
const response = await Book.aggregate([
{ $match: match },
{
$facet: {
edges: [{ $skip: skip }, { $limit: limit }],
pageInfo: [{ $group: { _id: null, count: { $sum: 1 } } }],
},
},
{
$project: {
_id: 0,
docs: "$edges",
totalDocs: { $first: "$pageInfo.count" },
page: `${page}`,
},
},
// { $group: { _id: null, count: { $sum: 1 } } },
]);
res.send(response[0]);
} catch (error) {
res.status(500).send(error);
}
});
app.listen(4000, () => {
console.log(`Server Running on 4000, `);
});