How to get parent document based on subdocument values ​​in Mongoose?

I have the following diagram:

var Child = new mongoose.Schema({ 'field': String, 'value': String }); var Parent = new mongoose.Schema({ 'name': String, 'children': [ Child ] }); 

I want to return a Parent for which one of Child matches the following JSON object:

 { 'field': 'Family Name', 'value': 'Smith' } 

I tried this:

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

but it continues to extract null .

EDIT:

Testing through the Mongo shell extension, I found that Child _id have their own _id . If you add this _id request to the request, it will select the Parent document. Now I do not know in advance what this id will be. So: how can I remove it from a request to a subquery? (In other words, the above query literally looks for a JSON object with two properties, and the subdocuments have three)

My environment: Node.js, Mongoose, MongoDB

+7
source share
2 answers

$elemMatch to be a query statement to solve this problem. The actual request should be written as follows:

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

Is there a reason why you are using a field, a value structure for child documents? It would be easier to just use the key as a field, for example {"FamilyName": "Smith"} . This will do something like:

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

All Articles