如何使用$ elemMatch与Mongoose Populated Virtual字段

时间:2018-06-06 20:17:19

标签: mongoose

我正在填充虚拟的一个Schema,虚拟包含一个对象数组。

我想要做的只是检索数组的一个对象,该对象符合我想要的标准,通常用$ elemMatch完成但是如何将它与Populate一起使用?

 //example
 var HouseHoldSchema = new Schema({
    name:String,
    pets:Array
 })

 var PersonSchema = new Schema({
    name:String
    pet:String
 });

 PersonSchema.virtual('animal',{
    ref:'Household',
    localField:'pet' //Person.pet
    foreignField:'pets.name' //HouseHold.pets[].name 
 });

假设我们有这些文件:

 //Person
 {  name: "George",
    pet:"Doggie"
 }

家庭

//Household
 { name: "Griffith
   pets:[
     {name:"Doggie", type:"Dog"},
     {name:"Kitty", type:"Cat"}
    ]
 }

我想填充'动物'虚拟,这是我尝试过但它仍将返回整个阵列

 Person.findOne({})
 .populate({
   path:'animal',
   select:'pets', //include only the pets[] field of Household
   options: {where:'pets',elemMatch:{name:'Doggie'}}
  )}
 .exec(function(err,docs){
    if(err) throw err

    console.log(docs);

  });

会打印

 { name:"George",
   pet:"Doggie",
   animal:[ {pets:[{name:"Doggie",type:"Dog"},{name:"Kitty",type:"Cat"}]} ]
  }

它返回整个数组,那么我怎么只让它打印“Doggie”对象?

0 个答案:

没有答案