I have the following schema's:
var Child = new mongoose.Schema({
'field': String,
'value': String
});
var Parent = new mongoose.Schema({
'name': String,
'children': [ Child ]
});
I want to return the Parent for which one of the Child's corresponds to the following JSON object:
{ 'field': 'Family Name', 'value': 'Smith' }
I have tried this:
Parent.findOne({ 'children': { 'field': 'Family Name', 'value': 'Smith' } }, fn ...)
but it keeps on retrieving null.
EDIT:
Testing through the Mongo shell extension, I found out that the Child sub-documents have their own _id's. If I add that _id to the query, it fetches the parent document. Now, I don't know in advance what that child id will be. So: how can I remove it from the sub-document query? (In other words, the above query literally looks for a JSON object with only two properties, while the sub-documents have three)
My environment is: Node.js, Mongoose, MongoDB
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){...});