From 0bcd5fc1f0ae42fcdc987fe3496848bed2ba8b44 Mon Sep 17 00:00:00 2001 From: Ricardo Castillo Date: Sat, 7 Sep 2024 11:53:12 -0400 Subject: [PATCH] Users can make comments on posts --- controllers/posts.js | 17 ++++++++++++++++- models/Comment.js | 18 ++++++++++++++++++ routes/posts.js | 2 ++ views/post.ejs | 18 ++++++++++++++++++ 4 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 models/Comment.js diff --git a/controllers/posts.js b/controllers/posts.js index a3e2dab5d..5e5e7a946 100644 --- a/controllers/posts.js +++ b/controllers/posts.js @@ -1,5 +1,6 @@ const cloudinary = require("../middleware/cloudinary"); const Post = require("../models/Post"); +const Comment = require("../models/Comment"); module.exports = { getProfile: async (req, res) => { @@ -21,7 +22,8 @@ module.exports = { getPost: async (req, res) => { try { const post = await Post.findById(req.params.id); - res.render("post.ejs", { post: post, user: req.user }); + const comments = await Comment.find({post: req.params.id}).sort({createdAt: "desc"}).lean() + res.render("post.ejs", { post: post, user: req.user, comments: comments }); } catch (err) { console.log(err); } @@ -73,4 +75,17 @@ module.exports = { res.redirect("/profile"); } }, + createComment: async (req, res) => { + try { + + await Comment.create({ + comment: req.body.comment, + post: req.params.id, + }); + console.log("Comment has been added!"); + res.redirect("/post/"+req.params.id); + } catch (err) { + console.log(err); + } + } }; diff --git a/models/Comment.js b/models/Comment.js new file mode 100644 index 000000000..333ac935e --- /dev/null +++ b/models/Comment.js @@ -0,0 +1,18 @@ +const mongoose = require("mongoose"); + +const CommentSchema = new mongoose.Schema({ + comment: { + type: String, + required: true, + }, + post: { + type: mongoose.Schema.Types.ObjectId, + ref: "Post", + }, + createdAt: { + type: Date, + default: Date.now, + }, +}); + +module.exports = mongoose.model("Comment", CommentSchema); \ No newline at end of file diff --git a/routes/posts.js b/routes/posts.js index aa463ac90..c8c488b22 100644 --- a/routes/posts.js +++ b/routes/posts.js @@ -13,4 +13,6 @@ router.put("/likePost/:id", postsController.likePost); router.delete("/deletePost/:id", postsController.deletePost); +router.post("/createComment/:id", postsController.createComment) + module.exports = router; diff --git a/views/post.ejs b/views/post.ejs index c36a1c946..3aa9085ef 100644 --- a/views/post.ejs +++ b/views/post.ejs @@ -22,6 +22,24 @@ <%}%> +

Comments:

+ +
+

Add a comment

+
+
+ + +
+ +
+