- I’m trying to make a blog. I want to comment on shared posts, comments are made and done well. It shares the views of the posts.
The solution I’m looking for is to make each post’s comments unique.
The IDs of the posts and comments should match and they should appear on the homepage without any problems, but I couldn’t do that.
` COMMENT AND POST SCHEMA'S `
` This is how my Post and Comment schemas link `
const commentSchema = new mongoose.Schema({ author: String, comment: String });
const Comment = mongoose.model("Comment", commentSchema);
const postSchema = new mongoose.Schema({
title: { required: true, type: String },
content: { type: String },
comments: [
commentSchema
]
});
const Post = mongoose.model("post", postSchema);
` Commenting codes like this `
` COMMENT APP `
app.post("/posts", (req, res) => {
const comment = new Comment({
author: req.user.username,
comment: req.body.comment
});
comment.save();
User.findOneAndUpdate({username: req.user.username}, {$push: {myComments: comment}}, function(err){
if(!err){
Post.findOneAndUpdate({}, {$push: {myComments: comment}}, function(err){
if(!err){
res.redirect("/posts");
}
})
}else{
console.log(err);
}
});
}); ```
` Here are the homepage codes where Posts and Comments appear. Where is the mistake? `
` POST AND COMMENT PAGE `
<% for(var i=posts.length; i--; i>-1){ %>
<div class="card">
<div class="card-body">
<h5>
<%=posts[i].title%>
</h5>
<p>
<%=posts[i].content%>
</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">
<form action="/posts" method="post">
<li class="list-group-item">
<div class="container">
<input class="comment" name="comment" type="text" placeholder=" Yorum Yaz">
<button class="button-commentAdd btn btn-success">Yorum Yap</button>
</div>
</li>
</form>
</li>
<% for(var j=comments.length; j--; j>-1){ %>
<li class="list-group-item">
<div class="container pt-2">
<div class="row">
<div class="col-12">
<p>
<strong>
<%= comments[j].author %>
</strong> <label>: </label>
<label> </label>
<%= comments[j].comment %>
</p>
</div>
</div>
</div>
</li>
<% } %>
</ul>
</div>
<% } %>