controller.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const Comment = require("./models/comment.js");
  2. module.exports = {
  3. /*
  4. GET: return all comments for the specific article
  5. req.params.article = String
  6. response = [Comment]
  7. */
  8. getComments: function(req, res){
  9. Comment.aggregate([
  10. {$match: {
  11. article: req.params.article
  12. }},
  13. {$sort: {
  14. date: -1
  15. }}
  16. ])
  17. .then((comments)=>{
  18. return res.json(comments);
  19. })
  20. .catch((err)=>{
  21. return res.json("Couldn't retrieve the comments");
  22. });
  23. },
  24. /*
  25. POST: create a new comment
  26. req.body = {
  27. article: String,
  28. name: String,
  29. content: String,
  30. date: Date
  31. }
  32. response = Comment
  33. */
  34. createComment: function(req, res){
  35. let comment = new Comment({
  36. article: req.body.article,
  37. name: req.body.name,
  38. content: req.body.content,
  39. date: new Date(req.body.date)
  40. });
  41. comment.save()
  42. .then((comment)=>{
  43. return res.json(comment);
  44. })
  45. .catch((err)=>{
  46. return res.json("Couldn't create your comment");
  47. });
  48. }
  49. }