-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
88 lines (78 loc) · 1.81 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
86
87
88
const express = require("express");
const mongodb = require("mongodb");
//app
const app = express();
//to use client in app
const db = require("./server").db();
//middlewares
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
//fronted engine
app.set("views", "views");
app.set("view engine", "ejs");
//routing
//create
app.post("/create-item", (req, res) => {
const title = req.body.title;
const body = req.body.body;
db.collection("notes_collection").insertOne(
{
title: title,
body: body,
createdAt: new Date().toISOString().split("T")[0],
},
(err, data) => {
res.json(data.ops[0]);
}
);
});
//update
app.post("/update-item", (req, res) => {
const { id, title, body } = req.body;
db.collection("notes_collection").findOneAndUpdate(
{ _id: new mongodb.ObjectId(id) },
{ $set: { title: title, body: body } },
(err, data) => {
res.json({ state: "success" });
}
);
});
//delete
app.post("/delete-item", (req, res) => {
const id = req.body.id;
if (!mongodb.ObjectId.isValid(id)) return res.json("Invalid ID");
db.collection("notes_collection").deleteOne(
{
_id: new mongodb.ObjectId(id),
},
(err, data) => {
if (err) {
return res.json("error");
} else {
res.json({ success: true });
}
}
);
});
//clear_all
app.post("/clear-all", (req, res) => {
if (req.body.clear_all) {
db.collection("notes_collection").deleteMany(() => {
res.json({ state: "cleared" });
});
}
});
// gett
app.get("/", (req, res) => {
db.collection("notes_collection")
.find()
.toArray((err, data) => {
if (err) {
console.log(er);
} else {
res.render("notes", { items: data });
}
});
});
module.exports = app;