1

I need to publish a simplified version of posts to users. Each post includes a 'likes' array which includes all the users who liked/disliked that post, e.g:

[
    { 
        _id: user_who_liked, 
        liked: 1 // or -1 for disliked 
    }, 
    ..
]

I'm trying to send a simplified version to the user who subscribes an array which just includes his/her like(s):

Meteor.publish('posts', function (cat) {
  var _self = this;
  return Songs.find({ category: cat, postedAt: { $gte: Date.now() - 3600000 } }).forEach(function (post, index) {
    if (_self.userId === post.likes[index]._id) {
      // INCLUDE
    } else
      // REMOVE

    return post;
  })
});

I know I could change the structure, including the 'likes' data within each user, but the posts are usually designed to be short-lived, to it's better to keep that data within each post.

4

1 回答 1

0

您需要使用此特定语法来查找具有likes包含数组的字段的帖子,该数组包含至少一个嵌入文档,该文档包含字段 by 和 value this.userId

Meteor.publish("posts", function (cat) {
  return Songs.find({
    category: cat,
    postedAt: { $gte: Date.now() - 3600000 },
    "likes._id":this.userId
  },{
    fields:{
      likes:0
    }
  });
});

http://docs.mongodb.org/manual/tutorial/query-documents/#match-an-array-element

编辑:以前使用的答案$elemMatch是不必要的,因为我们只需要过滤一个字段。

于 2015-04-23T16:20:27.733 回答