17
   db.History.find({'_file.project': 'someproject' )
      .populate('_file', 'name reference project')
      .sort(sortField || '-created')
      .limit(max || 64)
      .exec(this);

Here I'm trying to find all documents which match on a populated field from the _file reference. Is doesn't seem to work. Is something like this possible at all?

I could duplicate the project field to this object, as a workaround just for querying but I'd rather not of course.

Thijs Koerselman
  • 21,680
  • 22
  • 74
  • 108

1 Answers1

20

No, a find query's conditions parameter can only reference the collection being queried.

populate is not a join, it's just a convenience function to follow up the main query with additional queries to pull in the associated data from other collections.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • Thanks. So, just to be sure, in order to query the History collection based on project I will have to add the project field, duplicating it from the File model? Retrieving all documents and then filtering afterwards is not an option since the History collection is possibly very large. – Thijs Koerselman Jul 09 '13 at 08:28
  • 1
    @0x80 Right, or get all the `File` docs with matching `project` and then use an `$in` query against `History` using the `_id` values from the first query. – JohnnyHK Jul 09 '13 at 13:05
  • I get it now. It's good to know there are two options. Thanks! – Thijs Koerselman Jul 10 '13 at 07:59
  • This might have not existed when this was answered but the populate method supports a "match" property: ```populate({ path: 'notes', match: /airline/, select: 'text', model: 'modelName' options: opts }).```. http://mongoosejs.com/docs/api.html#document_Document-execPopulate – Doug Molineux Jan 18 '16 at 22:38
  • 10
    @DougMolineux The `match` option only controls which docs get their path populated after the main query completes. If the referenced doc doesn't match, the original reference id value remains unpopulated. – JohnnyHK Jan 18 '16 at 23:12
  • Ah I see what you mean! So it would not be relevant to the question, thank you – Doug Molineux Jan 21 '16 at 18:53
  • well, it could be ;). You could basically check after you get your result if your joined/matched dataset has been populated or not and remove it from your response – djnose Apr 10 '18 at 05:39