[英]How would I populate the mongoDB post schema with all comments for post?
我已經建立了兩種模式,一種用於帖子,一種用於評論。
const PostSchema = new Schema(
{
title: { type: String, required: true },
text: { type: String, required: true },
author: { type: Schema.Types.ObjectId, ref: 'User', required: true },
status: { type: Boolean, default: true },
},
{ timestamps: true }
);
, 和:
const CommentSchema = new Schema(
{
text: { type: String, required: true, minlength: 5 },
author: { type: String, required: true },
post: { type: Schema.Types.ObjectId, ref: 'Post' },
},
{
timestamps: true,
}
);
現在我想發出一個 GET 請求,它會找到所有帖子並用它的評論填充每個帖子。 到目前為止,我有這個,但我正在碰壁。 如果我嘗試這樣做,我無法添加.toArray()
,它甚至不會向 allPosts 添加新字段。
exports.allPosts_GET = (req, res) => {
Post.find()
.populate('author')
.sort('-createdAt')
.exec((err, allPosts) => {
if (err) {
return res.status(500).json({ success: false, msg: err.message });
} else if (allPosts.length === 0) {
return res.status(404).json({
success: false,
msg: 'No posts find in the database!',
});
}
allPosts.map((post) => {
post.comments = Comment.find({post: post._id}).
//to array somehow and populate all posts
});
console.log(allPostsStore);
res.status(200).json({ success: true, posts: allPosts });
});
};
所以我想出了一個解決方案,我更新了我的 Post 模式,其中包含一個引用評論 id 的數組。 像那樣:
const PostSchema = new Schema(
{
title: { type: String, required: true },
text: { type: String, required: true },
author: { type: Schema.Types.ObjectId, ref: 'User', required: true },
comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
status: { type: Boolean, default: true },
},
{ timestamps: true }
);
然后,當您發表新評論時,將其引用到帖子中,並將其保存到評論數組中,如下所示:
exports.createNewComment_POST = (req, res) => {
const { text, author, postID } = req.body;
const newComment = new Comment({
text,
author,
post: postID,
});
newComment
.save()
.then((comment) => {
Post.findByIdAndUpdate(
postID,
{ $push: { comments: comment._id } },
{ new: true, useFindAndModify: false },
(err, post) => {
if (err) {
return res.status(500).json({ success: false, msg: err.message });
}
res.status(200).json({ success: true, comment });
}
);
})
.catch((err) => {
res.status(500).json({ success: false, msg: err.message });
});
};
獲取所有帶有評論的帖子,您只需使用find()
和populate()
,就像這樣:
exports.allPosts_GET = (req, res) => {
Post.find()
.populate('author', '-password')
.populate('comments')
.sort('-createdAt')
.exec((err, posts) => {
if (err) {
return res.status(500).json({ success: false, msg: err.message });
} else if (posts.length === 0) {
return res.status(404).json({
success: false,
msg: 'No posts find in the database!',
});
}
res.status(200).json({ success: true, posts: posts });
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.