【问题标题】:Meteor collection.find - return multiple valuesMeteor collection.find - 返回多个值
【发布时间】:2014-05-23 08:04:37
【问题描述】:

我想在meteor 中结合meteor-roles 包实现通知功能,并且我想向角色中的所有用户显示相同的通知。 我认为将主要通知存储在通知集合中并在用户集合中存储对具有 id 和“读取”属性的通知的引用是一个好主意。 否则我需要为角色中的每个用户存储每个通知。

我的数据库:

User Collection: "username": "UserXYZ", "notifications": [[{ "_id": "231", "read": "false"}], [{ "id": "3234", "read": "true"}]] …
Notification Collection: "_id": "231" …

现在我想找到相应的通知,但问题是,我无法告诉查找函数我想要显示多个通知。

我认为这样的事情可以做到:

notifications: function() {
    var user = Users.findOne({_id: Meteor.userId()});
    return Notifications.find({_id: user.notifications._id, read: false});
}

任何帮助将不胜感激。

【问题讨论】:

  • mongo query operator $in 可以匹配一个数组而不是一个 _id。您需要遍历每个 user.notifications 来构造 _ids 数组。
  • 谢谢!工作!!! (Y)

标签: mongodb meteor


【解决方案1】:

您需要使用聚合来执行此操作。 $unwind 操作允许您对单个通知进行查询:

Users.aggregate(
    {$match: {_id: Meteor.userId()},
    {$unwind: "$notifications"},
    {$match: {"notifications.read": true}}
)

这会将每个通知作为其自己的文档返回。

【讨论】:

  • 感谢您的帮助。您能否告诉我如何使用 collection.find() 函数正确使用此聚合?我是这样尝试的:return Notifications.find(Users.aggregate( {$match: {_id: Meteor.userId()}}, {$unwind: "$notifications"}, {$match: {"notifications.read": false}} )); 但我总是收到“来自 Deps recompute”的异常。
  • @user3475602 您不能将聚合与.find 一起使用。这就是为什么它是一个单独的方法
  • 感谢您的回复。但是,在返回聚合时,我也遇到了异常。请告诉我如何正确使用它?我应该如何处理聚合查询;如何获取通知?
  • @user3475602 通常的方法可能是将回调传递给.aggregate 方法。 See the docs -- 这只是 .aggregate 与本机 MongoDB 驱动程序的第二个参数
  • 感谢您的链接。好吧,我尝试在客户端和服务器端执行该功能,但总是遇到异常。在服务器端:调用方法“comment”时出现异常类型错误:对象 [object Object] 没有方法“聚合”。我认为meteor不支持聚合函数。
猜你喜欢
  • 2013-04-04
  • 2015-02-09
  • 2016-03-20
  • 2010-09-29
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 2018-03-10
相关资源
最近更新 更多