diff --git a/controllers/comment.js b/controllers/comment.js new file mode 100644 index 000000000..2f6fd78f3 --- /dev/null +++ b/controllers/comment.js @@ -0,0 +1,17 @@ +const Comment = require("../models/Comment"); + +module.exports = { + postComment: async (req, res) => { + try { + const comment = await Comment.create({ + comment: req.body.comment, + post: req.params.id + }); + console.log(`Comment Added: ${req.body.comment}`); + res.redirect(`/post/${req.params.id}`); + } + catch (err) { + console.log(`Comment could not be generated → ${err}`) + } + } + } \ No newline at end of file diff --git a/controllers/posts.js b/controllers/posts.js index a3e2dab5d..00d56f6d2 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); } diff --git a/models/Comment.js b/models/Comment.js new file mode 100644 index 000000000..05be77664 --- /dev/null +++ b/models/Comment.js @@ -0,0 +1,22 @@ +const mongoose = require("mongoose"); + +const CommentSchema = new mongoose.Schema({ + comment: { + type: String, + required: true, + }, + post: { + type: mongoose.Schema.Types.ObjectId, + ref: "Post", + }, + user: { + type: mongoose.Schema.Types.ObjectId, + ref: "User", + }, + 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..22d1c5659 100644 --- a/routes/posts.js +++ b/routes/posts.js @@ -2,15 +2,16 @@ const express = require("express"); const router = express.Router(); const upload = require("../middleware/multer"); const postsController = require("../controllers/posts"); +const commentController = require("../controllers/comment") const { ensureAuth, ensureGuest } = require("../middleware/auth"); //Post Routes - simplified for now router.get("/:id", ensureAuth, postsController.getPost); router.post("/createPost", upload.single("file"), postsController.createPost); - router.put("/likePost/:id", postsController.likePost); - router.delete("/deletePost/:id", postsController.deletePost); +router.post("/postComment/:id", ensureAuth, commentController.postComment) + module.exports = router; diff --git a/views/post.ejs b/views/post.ejs index c36a1c946..bf74436c7 100644 --- a/views/post.ejs +++ b/views/post.ejs @@ -27,6 +27,25 @@

<%= post.caption %>

+ +
+

Add comment

+
+
+ + +
+ +
+
+ +
Return to Profile Return to Feed