2015-11-27 57 views
1

我收集了一個集合Projects和一個集合Questions。每個Project都有一個「已接受」的文檔,以及一系列已接受的用戶。 每個Question都有一個projectId項目文件。流星計數兩個集合的值

示例情況:
有6個問題。項目1有兩個問題,項目2有兩個問題,項目3有兩個問題。
用戶X已接受項目2和項目3.

我想返回用戶X得到的問題數量。

return Projects.find({accepted: currentUser}); // Gives two projectId's 

,然後將每個專案編號:

return Questions.find({project: <projectId>}).count(); 

,並添加爲每個專案編號問題,所有金額。

我該怎麼做?

你的, 大號

+0

你能與預期結果對您的問題加樣的文件? – styvane

+0

'return Questions.find({project:{$ in:[projectIds]}})。count();' – richsilv

回答

0

而不是創建每個項目ID的多步驟的查詢,你可以使用匹配任何被從初始查詢返回的ID的單個MongoDB的選擇。

該選擇器將是$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();