可以在数组中找到一个对象,即在数组的对象中?

时间:2017-03-22 18:26:22

标签: node.js mongodb mongoose mongoose-schema

我有一个类似这样的架构:

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

我的查询如下:

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

正如所料,我得到了正确的父元素。但是,正如您所看到的那样,父元素有一个包含子元素的数组。无论如何mongoose可以在子数组中给我一个对象吗?或者我需要自己找到它?

先谢谢了。

1 个答案:

答案 0 :(得分:1)

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.