我得到了一个Projects
集合和一个Questions
集合。每个项目
都有一个“已接受”文档,其中包含一组已接受的用户。
每个问题
都有一个带有projectId的文档“Project”。
示例情况:
有6个问题。项目 1 有 2 个问题,项目 2 有 2 个问题,项目 3 有 2 个问题。
用户X已接受项目2和项目3。
我想返回用户 X 的问题数量。
return Projects.find({accepted: currentUser}); // Gives two projectId's
然后是每个projectId:
return Questions.find({project: <projectId>}).count();
并添加每个项目 ID 的所有问题数量。
我该怎么做?
你的, 升
最佳答案
您可以使用与初始查询返回的任何 ID 相匹配的单个 mongodb 选择器,而不是为每个项目 ID 创建多步查询。
其选择器为 $in
The $in operator selects the documents where the value of a field equals any value in the specified array.
因此,对于您的情况,解决方案是:
// get the current user's id (you can use this.userId if you are in a method or a publication
const currentUser = Meteor.userId();
// we want an array of _id's only
const projectIds = Projects.find({accepted: currentUser}).map(function(project) {
return project._id;
})
// now we use the $in operator
return Questions.find({project: {$in: projectIds} }).count();
关于javascript - meteor 数二的收藏值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33957787/