MongoDB: Match with object in array

Hey guys,
I’m working on my publications and now having the following problem:

I’ve a chat collection, where every chat document has an array with user objects in it, f.e:

Chat:

{
  _id:'abcdef'
 users: [{id:'ysdf'},{id:'ttzufd'}]
} 

Now I try to get the users with the following query:

chat = Chat.find('abcdef');
return Meteor.users.find({_id:{$in:chat.users.$.id}}, {fields: {
            status: 1,
            username:1,
            profile:1
        }});

…but that’s not working. What would be the correct way? At the moment, my only idea is using underscore _.each() and add the ids to a new array.

var chat = Chat.findOne({ _id: 'abcdef' });
var chatUsers = chat.users.map(function (item) {
    return item.id;
});
return Meteor.users.find({ _id: { $in: chatUsers } }, {
        fields: {
            status: 1,
            username: 1,
            profile: 1
        }
    });
1 Like

Under normal circumstances (no autopublish), the Meteor.users collection only publishes the current user. You probably need to either publish the required users yourself, or copy the actual user record into your chat (the fields you need to expose).

Hey,
yeah I know, I just didn’t recognize that I’ve mixed Mongo syntax with pure JS syntax above, so it’s logical that “chat.users.$.id” can’t work, because it is a pure JS array and not a Mongo document. I’m now using the solution from @hellstad (thanks).

Meteor.users.find({
  _id: {
    $in: Chat.find('abcdef').map(function (doc) {
      return doc._id
    });
  }
});