Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion controllers/posts.js
Original file line number Diff line number Diff line change
@@ -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) => {
Expand All @@ -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);
}
Expand Down Expand Up @@ -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);
}
}
};
18 changes: 18 additions & 0 deletions models/Comment.js
Original file line number Diff line number Diff line change
@@ -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);
2 changes: 2 additions & 0 deletions routes/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
18 changes: 18 additions & 0 deletions views/post.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,24 @@
<button class="btn btn-primary fa fa-trash" type="submit"></button>
</form>
<%}%>
<h3>Comments:</h3>
<ul>
<% for(var i=0; i<comments.length; i++) {%>
<li class="col-6 justify-content-between mt-5">
<%= comments[i].comment%>
</li>
<% } %>
</ul>
<div class="mt-5">
<h2>Add a comment</h2>
<form action="/post/createComment/<%=post._id%>" method="POST">
<div class="mb-3">
<label for="caption" class="form-label">Comment</label>
<textarea class="form-control" id="caption" name="comment"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
<div class="col-3 mt-5">
Expand Down