-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcandidates.js
67 lines (55 loc) · 1.79 KB
/
candidates.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
import db from "./mongodbconn.js";
import express from "express";
import { ObjectId } from "mongodb";
const router = express.Router();
let index = 5;
router.get("/", async (req, res) => {
let collection = await db.collection("candidates");
let query = {
...(req.query.fname ? { fname: req.query.fname } : {}),
...(req.query.lname ? { lname: req.query.lname } : {}),
...(req.query.email ? { email: req.query.email } : {}),
};
let results = await collection.find(query).limit(50).toArray();
res.send(results).status(200);
});
router.get("/:id", async (req, res) => {
let collection = await db.collection("candidates");
let query = { id: parseInt(req.params.id) };
let result = await collection.findOne(query);
if (!result) res.send("Not found").status(404);
else res.send(result).status(200);
});
router.post("/", async (req, res) => {
let collection = await db.collection("candidates");
let newDocument = {
id: index++,
fname: req.body.fname,
lname: req.body.lname,
email: req.body.email,
score: req.body.score,
};
let result = await collection.insertOne(newDocument);
res.send(newDocument).status(204);
});
router.put("/:id", async (req, res) => {
const query = { id: parseInt(req.params.id) };
const updates = {
$set: {
fname: req.body.fname,
lname: req.body.lname,
email: req.body.email,
score: req.body.score,
},
};
let collection = await db.collection("candidates");
let result = await collection.updateOne(query, updates);
res.send(result).status(200);
});
router.delete("/:id", async (req, res) => {
const query = { id: parseInt(req.params.id) };
const collection = db.collection("candidates");
let result = await collection.deleteOne(query);
res.send(result).status(200);
});
export default router;