It has been a few days after I post this question and I have received no answer so far. But I have figure out why my code is not working and this post will try to answer this question I asked a few days ago and hope it can help some who is struggling the same issue.
My problems here are each comment created can not been pushed into the array of comments in Post, so the comments can not be displayed as the array is empty.
If you look at my code for Schema, you might realized that I made mistake for comment schema as I did not define a post key value pair, so the correct comment and post schema should be as below. The logic here is that each blog post can has multiple comments below, so the comments in post Scheme should be created as a array, but each comment can only below to one of the post, therefore the post key value pair in comment schema should be only in a object
const mongoose = require('mongoose');
const commentSchema = new mongoose.Schema({
text: {
type: String,
trim: true,
required: true
},
date: {
type: Date,
default: Date.now
},
// each comment can only relates to one blog, so it's not in array
post: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
})
module.exports = mongoose.model('Comment', commentSchema);
and the post schema should be as below
const mongoose = require('mongoose');
const postSchema = new mongoose.Schema({
title: {
type: String,
trim: true,
required: true
},
text: {
type: String,
trim: true,
required: true
},
date: {
type: Date,
default: Date.now
},
// a blog post can have multiple comments, so it should be in a array.
// all comments info should be kept in this array of this blog post.
comments: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}]
})
postSchema.virtual('url').get(function(){
return '/post/' + this._id
})
module.exports = mongoose.model('Post', postSchema);
Another important thing I did not do was, every time a comment was posted, this comment should be pushed into the post.comments array. I did not do this step, that's why my array was always empty and there is no comment to display. the code to correct this is go to file commentRouter.js (I have created both of postRouter.js and commentRouter.js), add code below
router.post('/post/:id/comment', async (req, res) => {
// find out which post you are commenting
const id = req.params.id;
// get the comment text and record post id
const comment = new Comment({
text: req.body.comment,
post: id
})
// save comment
await comment.save();
// get this particular post
const postRelated = await Post.findById(id);
// push the comment into the post.comments array
postRelated.comments.push(comment);
// save and redirect...
await postRelated.save(function(err) {
if(err) {console.log(err)}
res.redirect('/')
})
})
the above is how I fixed my error, hope it can help someone.
Thank you for reading