Skip to content
21 changes: 20 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");
import Comments from '../models/comments'

module.exports = {
getProfile: async (req, res) => {
Expand All @@ -21,7 +22,11 @@ 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 Comments.findAll({postID : 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 +78,18 @@ module.exports = {
res.redirect("/profile");
}
},
addComment: async(req,res)=>{
try{
await Comments.create({
commentText: req.body.commentText,
userName : req.user.id,
postID : req.params.id

});
console.log('comment added!')
res.redirect(`/post/${req.params.id}`)
}catch(err){
console.err(err)
}
}
};
21 changes: 21 additions & 0 deletions models/comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import mongoose from 'mongoose'

const CommentSchema = new mongoose.Schema({
commentText: {
type: String,
required: true,
},
userName: {
type: String,
require: true,
},
postID: {
type: mongoose.Schema.Types.ObjectId
},
createdAt: {
type: Date,
default: Date.now,
},
});

module.exports = mongoose.model("Comments", CommentSchema);
2 changes: 2 additions & 0 deletions routes/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ router.post("/createPost", upload.single("file"), postsController.createPost);

router.put("/likePost/:id", postsController.likePost);

router.post('/addComment/:id', ensureAuth, postsController.addComment)

router.delete("/deletePost/:id", postsController.deletePost);

module.exports = router;
25 changes: 24 additions & 1 deletion views/post.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,30 @@
>
<button class="btn btn-primary fa fa-trash" type="submit"></button>
</form>
<%}%>
<%}else{%>
<form
action="/post/addComment/<%= post.id %>"
method="POST"
class="col-3"
>
<input type="text" name="commentText">
<button class="btn btn-primary fa fa-pen" type="submit"></button>
</form>
<%}%>

<%if(comments.length > 0){ %>
<div id="commentContainer"></div>
<% for (let i = 0; i < comments.length; i++) { %>
<div id="individualComment">
<h3><%= comments.userName %> </h3>
<span><%= comments.commentText %></span>
</div>
<% } %>
</div>


<%}%>

</div>
</div>
<div class="col-3 mt-5">
Expand Down