Javascript 流星计数两个集合的价值

Javascript 流星计数两个集合的价值,javascript,mongodb,meteor,Javascript,Mongodb,Meteor,我得到了一个集合项目和一个集合问题。每个项目都有一个文档“已接受”,包含一组已接受的用户。 每个问题都有一个带有projectId的文档“Project” 示例情况: 有6个问题。项目1有两个问题,项目2有两个问题,项目3有两个问题用户X已接受项目2和项目3 我想返回用户X的问题数量 return Projects.find({accepted: currentUser}); // Gives two projectId's 然后每一个投影: return Questions.find({pr

我得到了一个集合
项目
和一个集合
问题
。每个
项目
都有一个文档“已接受”,包含一组已接受的用户。 每个
问题
都有一个带有projectId的文档“Project”

示例情况:
有6个问题。项目1有两个问题,项目2有两个问题,项目3有两个问题
用户X已接受项目2和项目3

我想返回用户X的问题数量

return Projects.find({accepted: currentUser}); // Gives two projectId's
然后每一个投影:

return Questions.find({project: <projectId>}).count();
返回问题。查找({project:}).count();
并为每个项目添加所有数量的问题

我该怎么做

你的,
L

您可以使用一个mongodb选择器来匹配初始查询返回的任何Id,而不是为每个项目Id创建多步骤查询

这方面的选择是

$in运算符选择字段值等于指定数组中任何值的文档

因此,在您的情况下,解决方案是:

// 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();

您可以使用一个mongodb选择器来匹配初始查询返回的任何Id,而不是为每个项目Id创建多步骤查询

这方面的选择是

$in运算符选择字段值等于指定数组中任何值的文档

因此,在您的情况下,解决方案是:

// 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();

能否将具有预期结果的示例文档添加到问题中?
返回问题。查找({project:{$in:[projectds]}).count()
能否将具有预期结果的示例文档添加到问题中?
返回问题。查找({project:{$in:[projectds]}).count()