我是Nodejs和Mongosee的新手,这在Php和Mysql中很简单,有许多解决方案,但不知道如何在Mongosee和Nodejs中进行查询 这是我的代码 发布架构
import mongoose from 'mongoose';
const postSchema = new mongoose.Schema({
title: String,
description: String
});
const postModel = mongoose.model('post', postSchema);
export default postModel;
评论模式
import mongoose from 'mongoose';
const commentSchema = new mongoose.Schema({
postId: {
ref: 'post',
type: mongoose.Schema.Types.ObjectId
},
title: String,
content: {
type: String,
required: true
}
});
const commentModel = mongoose.model('comment', commentSchema);
export default commentModel;
如何查询类似结果
{
"_id": "5e7c7217068570095363ecb0",
"title": "Test Post ",
"description": "My description",
"__v": 0,
"comment_count": 10,
},
{
"_id": "5e7c7218068570095363ecb1",
"title": "Test Post ",
"description": "My description",
"__v": 0,
"comment_count": 0,
}
答案 0 :(得分:2)
您可以使用以下汇总
const posts = await Post.aggregate([
{
$lookup: {
from: "comments",
let: { postId: "$_id" },
pipeline: [{ $match: { $expr: { $eq: ["$$postId", "$postId"] } } }],
as: "comment_count"
}
},
{ $addFields: { comment_count: { $size: "$comment_count" }}}
]);