-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContentController.js
86 lines (75 loc) · 2.42 KB
/
ContentController.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
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));
router.use(bodyParser.json());
const Content = require('./Content');
// ADD NEW CONTENT
router.post('/create/content', (req, res) => {
Content.create({
author: req.body.author,
title: req.body.title,
body: req.body.body,
published_on: req.body.published_on,
},
(err, content) => {
if (err) {
return res.send("There was a problem while adding the information to the database.")
}
res.send(content)
})
})
// GET ALL CONTENT FROM DB
router.get('/', (req, res) => {
Content.find({}, (err, content) => {
if (err) {
return res.json(err)
}
res.send(content)
})
})
// GET A PARTICULAR CONTENT (using /:id)
router.get('/get/:id', (req, res) => {
Content.findById(req.params.id, (err, content) => {
if (err) {
return res.send("There was a problem in finding the specified content.")
}
if (!content) {
return res.send("No content found.")
}
res.send(content);
})
})
// UPDATE A PARTICULAR CONTENT IN THE DATABASE
router.put('/update/:id', (req, res) => {
Content.findByIdAndUpdate(req.params.id, req.body, {new: true}, (err, content) => {
if (err) {
return res.send("There was a problem in updating the content.")
}
res.send(content)
})
})
// DELETE A PARTICULAR CONTENT FROM THE DATABASE
router.delete('/del/:id', (req, res) => {
Content.findByIdAndRemove(req.params.id, (err, content) => {
if (err) {
return res.send("There was a problem deleting the content.")
}
res.send("Content of author: '"+ content.author +"' having title: '"+ content.title +"' was deleted.")
})
})
// SEARCH A PARTICULAR AUTHOR FROM THE DATABASE (CASE-SENSITIVE)
router.get("/search/:author", (req, res) => {
var regex = new RegExp(req.params.author)
Content.find({author: regex}).then((result) => {
res.status(200).json(result)
})
})
// SEARCH A PARTICULAR AUTHOR FROM THE DATABASE (CASE-INSENSITIVE)
router.get("/search/any/:author", (req, res) => {
var regex = new RegExp(req.params.author, "i")
Content.find({author: regex}).then((result) => {
res.status(200).json(result)
})
})
module.exports = router;