How to retrieve parent document based on subdocument values in Mongoose? How to retrieve parent document based on subdocument values in Mongoose? mongoose mongoose

How to retrieve parent document based on subdocument values in Mongoose?


It seems the $elemMatch is the query operator to solve this problem. The actual query should be written as follows:

Parent.findOne({ 'children': { $elemMatch: { 'field': 'Family Name', 'value': 'Smith' } } }, fn ...)


Is there a reason you use field, value structure on the child documents? It would be easier to simply use the key as the field, like {"FamilyName": "Smith"}. This would allow something like:

Parent.findOne({'children.FamilyName': 'Smith'}, function(err, doc){...});