如何解决如何以正确的方式组合 2 个集合一对多猫鼬?
我从猫鼬开始,努力解决一个微不足道的问题。
我在下面有一个可行的解决方案,但我觉得这是错误的,应该是更简单的方法。
我有 2 个收藏集:帖子和评论。
当我获取帖子时,我还想附上评论数。 (如果更简单,它可以是一组 ID)
应该可以使用正确的架构定义和虚拟对象,但我没有这样做。
期望的结果
[
{ title: 'post 1',comments: 2 },{ title: 'post 2',comments: 0 }
]
我目前的解决方案是:
// Models
const PostSchema = new Schema({
title: String
});
const CommentSchema = new Schema({
postId: {
type: mongoose.Schema.Types.ObjectId,ref: 'Post'
},text: String
});
// controller
exports.getAll = async (req,res) => {
let postsWithCommentCount = [];
const posts = await Post.find({ }); // get all posts
const comments = await Comment.aggregate([ {$group: { _id: '$postId',comments: { $sum: 1}}} ])
postWithCommentCount = posts.map(post => {
const postWithComments = comments.find(c => c._id.equals(post._id));
return { ...post.toJson(),comments: postWithComments ? postWithComments.comments : 0 };
});
res.json(postWithCommentCount);
};
提前致谢
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。