猫鼬-如何在猫鼬的填充字段数组中选择特定对象?

时间:2018-06-24 14:38:15

标签: node.js mongodb mongoose

我已经在Mongoose中填充了一个虚拟对象,填充的虚拟对象将检索对象数组。

 objects:{[name:'xxx',age:20],[name:'yyy',age:21],[name:'zzz', age:23]}

如何使它仅检索指定的一个元素?

...
.populate({
   path:'someVirtual',
   select:'objects', //get only the 'objects' array
   options: {where:'objects',elemMatch:{name:'zzz'}} //this is what I tried 
                                                     //but it doesn't work
  )}
 .exec(function(err,docs){
    //handle
  });

1 个答案:

答案 0 :(得分:0)

您可以在填充中使用match

.populate({
   path:'someVirtual',
   match: { objects: { $elemMatch: { name: 'zzz' } } },
   select: 'objects'                                        
})

如果要使用投影,则

.populate({
   path:'someVirtual',
   match: { objects: { $elemMatch: { name: 'zzz' } } },
   select: { objects: { $elemMatch: { name: 'zzz' } } }                                   
})