我如何使用 post 的所有评论填充 mongoDB post 架构?
How would I populate the mongoDB post schema with all comments for post?
我已经构建了两个模式,一个用于 posts,一个用于评论。
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 请求,该请求会找到所有 post 并用其注释填充每个 post。到目前为止我有这个,但我碰壁了。如果我尝试这样做,我无法添加 .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 }
);
然后当你发表新评论时,你将其引用到 post,并将其保存到评论数组中,如下所示:
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 });
});
};
获取所有 post 的评论,您只需使用 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 });
});
};
我已经构建了两个模式,一个用于 posts,一个用于评论。
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 请求,该请求会找到所有 post 并用其注释填充每个 post。到目前为止我有这个,但我碰壁了。如果我尝试这样做,我无法添加 .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 }
);
然后当你发表新评论时,你将其引用到 post,并将其保存到评论数组中,如下所示:
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 });
});
};
获取所有 post 的评论,您只需使用 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 });
});
};