Meteor : filter a publication on a nested property

collections, javascript, meteor, mongodb

Solution

I appears that you can simply do :

`Companies.find({'customers._id': this.userId}, {fields: {'stores': 1, 'customers': 1}});`

This will search inside the array.

But now, how to finish the filter and return only the customer's informations and not the informations of all the company's customer ?

And the answer is in the mongo doc again !

I appears that you can add a projection on a field. ( http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/#proj._S_elemMatch )

The final request with the proper filters is : `return Companies.find({'customers._id': this.userId}, {fields: {'stores': 1, 'customers': { $elemMatch: { _id: this.userId } }}});`

(I was not that hard in the end, but if my answer can help someone... :) )

Problem

I have a simple publication : `return Companies.find({}, {fields: {'myField1': 1, 'myField2': 1}});` In my `Companies` collections, for each company I have an array `customers` and an array `managers`. Those array contains objects with '_id' and various other property. For visualization, an new company might be added as follows: ``` Companies.insert({ customers: [{_id: <userId>, otherProp: <data>}, ...], managers: [{_id: <userId>, otherProp: <data>}, ...] }); ``` This `_id` field is the id of the corresponding user in the users collection. I would like to return only the companies where you can find the _id of the user in one of the objects of the customers array (or the managers array, depending of the user). This is probably a mongo question, but I'm not sure. => in the documentation, they mentions the mongo selectors : http://docs.meteor.com/#selectors ( http://docs.mongodb.org/manual/reference/operator/query/ ) But I cannot figure out how to use that for my case.

Original source