javascript - meteor 数二的收藏值(value)

标签 javascript mongodb meteor

我得到了一个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/

相关文章:

javascript - 加载脚本失败 - Webworker (PDF.JS)

node.js - 无法使用 Mongoose 保存

javascript - 自动更新提交日期的 timeAgo 值

css - 无法在 Meteor 中解码下载的字体

javascript - HTML 输入类型 ="time"只允许 15 分钟间隔

javascript - 在javascript中按值浏览json

javascript - 了解 call() 函数和对象

mongodb - 限制 mongodb 集合中的文档数量,没有 FIFO 策略

java - 使 Quartz 调度程序在没有 JDBC 的情况下持久化

javascript - 如何判断 Meteor minimongo 何时与 mongo 服务器同步