-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
119 lines (98 loc) · 2.75 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
const express = require("express");
const mongoose = require("mongoose");
const ejs = require("ejs");
const bodyParser = require("body-parser");
const app = express();
//EJS setup
app.set("view engine", "ejs");
//BodyParser setup
app.use(bodyParser.urlencoded({ extended: true }));
//public folder setup
app.use(express.static("public"));
// MONGODB URL
const MongoDB_URL = `mongodb+srv://reaperhound:[email protected]/wikiDB`;
//Mongo connect
mongoose
.connect(MongoDB_URL)
.then(() => console.log(`Connected to MongoDB`))
.catch((err) => console.log(err));
mongoose.set("strictQuery", false);
//Mongo Schema
const wikiSchema = {
title: String,
content: String,
};
//Mongo model
const Wiki = mongoose.model("articles", wikiSchema);
// ----------------------------
//setting up server
app.listen(3000 || process.env.PORT, () => console.log(`server started at PORT 3000`));
// // Articles GET route
// app.get(`/articles`);
// //Articles POST route
// app.post(`/articles`);
// //Articles DELETE route
// app.delete(`/articles`);
////////////////////////////////////// Request Targeting all Articles //////////////////////////////////////////
app
.route(`/articles`)
.get((req, res) => {
Wiki.find()
.then((foundArticles) => {
res.send(foundArticles);
})
.catch((err) => res.send(err));
})
.post((req, res) => {
const newArticle = new Wiki({
title: req.body.title,
content: req.body.content,
});
newArticle
.save()
.then(() => res.send(`Successfully added`))
.catch((err) => res.send(err));
})
.delete((req, res) => {
Wiki.deleteMany()
.then(() => res.send(`Successfully deleted`))
.catch((err) => res.send(err));
});
////////////////////////////////////// Request Targeting Specific Article //////////////////////////////////////////
app
.route(`/articles/:article`)
.get((req, res) => {
Wiki.findOne({ title: req.params.article })
.then((articleFound) => {
res.send(articleFound);
})
.catch((err) => res.send(err));
})
.put((req, res) => {
Wiki.findOneAndReplace(
{ title: req.params.article },
{
title: req.body.title,
content: req.body.content,
}
)
.then(() => res.send(`Successfully Updated`))
.catch((err) => res.send(err));
})
.patch((req, res) => {
Wiki.findOneAndUpdate(
{
title: req.params.article,
},
{ $set: req.body }
)
.then(() => res.send(`Updated successfully`))
.catch((err) => console.log(err));
})
.delete((req, res) => {
Wiki.findOneAndDelete({
title: req.params.article,
})
.then(() => res.send("Successfully deleted Document"))
.catch((err) => res.send(err));
});