Mongo - 如何返回字段在另一个集合数组中的集合?

时间:2016-03-31 21:16:35

标签: mongodb meteor coffeescript

我正在使用Meteor与Mongo。 我有一个Notifications集合,我正在插入以下代码(coffeescript) -

    Notifications.new
      title: Meteor.user().username + ' liked your listing'
      link: '/listing/' + $(e.currentTarget).attr('doc')
      icon: 'thumbs-up'
      class: 'default'
      target: $(e.currentTarget).attr('doc')

基本上我想做的是向创建列表的用户返回通知(集合中的'target'字段是列表ID)。

我尝试插入$(e.currentTarget).attr('doc')。createdBy但是它没有用。 (我对这个东西不熟悉)

如果我能找到一种方法在通知中插入createdBy,那么一切都会更好地结合在一起,但我无法找到一种方法。

我的另一个想法是尝试做这样的事情 - 我的用户集合中有一个列表数组*

Meteor.publish 'notifications', ->
   Notifications.find {**** return Notifications where their target ID is in the current User listing array ****}

有人对此有任何想法吗? 非常欣赏它。 感谢

1 个答案:

答案 0 :(得分:0)

基本上,您需要首先查找列表并获取创建该列表的用户的_id

let listingId = $(e.currentTarget).attr('doc');

// assuming that the Listings collection has such a key
// AND that the Listing referred to is published to the current user

let createdById = Listings.findOne(listingId).createdById;

Notifications.new
  title: Meteor.user().username + ' liked your listing'
  link: '/listing/' + $(e.currentTarget).attr('doc')
  icon: 'thumbs-up'
  class: 'default'
  target: createdById

如果您没有跟踪列表文档中的创建者_id,而是跟踪在用户文档中创建的列表,那么您需要搜索Meteor.users集合:< / p>

let createdById = Meteor.users.findOne({listings: listingId})._id;