我有这段代码,一本书可以有很多注释,我想将它们的数量放在数组中
const bookCommentsLoader = new DataLoader(async bookIds => {
const comments = await Comment.count({
bookId: { $in: bookIds }
})
...
})
graphql数据加载器的问题在于,返回时,id的结果和长度必须匹配,所以我希望它返回以下内容:
model id-> ['1','3','12'] must return model counts like [5,7,1]
我不想使用循环提示,它将发送多个查询,我想使用单个查询,帮助吗?
答案 0 :(得分:0)
https://docs.mongodb.com/manual/reference/operator/aggregation/sum/#grp._S_sum
您将使用汇总
var aggregatePipeline = [
{$group: {_id: "$bookId", numOfComments: {$sum: 1}}
];
Comments.aggregate(aggregatePipeline, (error, results) => {
// results comes out to be [{_id: bookId, numOfComments: Number}, ....]
// From here, you can map the array to the format you wish
var formattedArray = results.map(o => return(o.numOfComments))
console.log(formattedArray);
});