Mongodb - returning array field

I have a collection (UserData) that contains an array with id’s (news) of documents from another collection (News).

Meteor.publish('user-news', function() {
  var a = UserData.find({_id: this.userId}, {fields: {_id: 0, news: 1}}).fetch();
  return News.find({_id: {$in: a}});
});

Document structure:

{
    "_id" : "9PBX38WYi93XQqYGh",
    "news" : [ 
        "cfPY52bjfieoLy7eE",
        "jggqssAZjT2DBSgbP",
        "Tg3KGdd4PADtfqBZE"
    ]
}

Any idea what I’m doing wrong?

  1. you cant omit an _id field - it returned by default
  2. after fetch you’ll have an array of OBJECTS, so your news ids would be placed in {news: []}
  3. use each, map or reject for the cursor

See next:

var newsIds = UserData.find({_id: this.userId}, {fields: {news: 1}}).map(function(doc) {return doc.news|| []});
newsIds = _.flatten(newsIds);
return News.find({_id: {$in: newsIds}});
2 Likes

Works just perfect!
Thanks a bunch!