Search code examples
node.jsmongodbmongoosemongoose-schema

Possible to find a object in a array, that is in a object of arrays?


I have a schema like looks like this:

 parent: [{
                year: Number,
                kind: String,
                child:  [{age: Number, value: Number}]
            }],

My query looks like this:

myDB.findOne({'parent.year': year, 'parent.kind': kind})
.where('parent.child.age').equals(age)

As expected, I get the correct parent element. But that parent element, as you can see, has an array with children. Is there any way mongoose can give me a single object in the child array? Or do I need to find it myself?


Solution

  • An aggregate will work for this. The $unwind command will create a document for each entry in the array:

    myDB.aggregate([
       {$unwind:'$parent.child'},
       {$match:{
          'parent.year':year, 
          'parent.kind':kind,
           'child.age':age}
        },
        {$limit:1}
      ], function(err,doc) {
         //Do stuff here with doc
     });
    

    If you need to return the other children you will need to regroup the unwind results which is a little bit more complicated but is very doable.