Austin Gayler
Austin Gayler

Reputation: 4356

Finding nested array data with elemMatch in MongoDB/Meteor

collection structure as such:

{"_id" : "abc",
"potentialUsers" : [{"userID" : "def"}, 
                    {"userID" : "ghi"}]
},

{"_id" : "123",
"potentialUsers" : [{"userID" : "456"}, 
                    {"userID" : "789"}]
},

I want to query if user abc has the user def in their potential users array. My current query (client) is

    getPendingLiftRequests: function() {
        return collection.find({}, {potentialUsers: {$elemMatch: {userID: Meteor.user().services.facebook.id}}});
    }

On the server I publish all of that collection to the user, and then just selectively show it based on the view of the client. However, when I try to use an elemMatch on the array, it just shows all of the records, when it should only show 1.

Upvotes: 1

Views: 2055

Answers (2)

Stuiterbal
Stuiterbal

Reputation: 457

Have look at the documentation for minimongo in Meteor: http://docs.meteor.com/#/full/find

You have to use the fields option to get the desired result.

getPendingLiftRequests: function() {
    return collection.find({}, { fields: { potentialUsers: {$elemMatch: {userID: Meteor.user().services.facebook.id}}}});
}

Upvotes: 2

David Weldon
David Weldon

Reputation: 64312

You don't need $elemMatch here. This should work:

var fId = Meteor.user().services.facebook.id;
return collection.find({'potentialUsers.userID': fid});

Upvotes: 2

Related Questions