查询填充字段

时间:2015-05-15 20:01:38

标签: javascript node.js mongodb mongoose

目前,我有两种模式:

var person = new schema({
id: Number,
name: String,
city: {
    type: schema.Types.ObjectId,
    ref: 'cities'
}
});

var city = new schema({
id: Number,
name: String,
country: String,
country_short: String
});

我有两个模特:

var persons = mongoose.model('persons', person);
var cities = mongoose.model('cities', city);

一切顺利。我可以选择一个人并让它在city点上返回city对象,完美!

问题:

我想选择所有拥有country_short" NL"的城市的人。我试过这个:

persons.find({
  'city.country_short': 'NL'
}).populate('city').exec(function(err, data) {
  //Data SHOULD obtain all persons living in a city with country_short "NL".
});

这不起作用。我找到了一个有效的解决方案,但它已经嵌套了......我不喜欢它。它选择country_short' NL'并映射它们。然后WITHIN找到(嵌套...)我找到所有人并在映射数组中检查city $。

帮助我找到一个非巢穴解决方案。或者也许是另一种方式。

谢谢!!!!

1 个答案:

答案 0 :(得分:0)

要在 populating 中包含引用架构的查询条件,请使用以下方法:

persons.find(...)
       .populate({
           path: 'city',
           match: { country_short: 'NL'},
           select: 'name -_id', /* limit fields to return */
           options: { limit: 5 } /* limit documents to return */
       })
       .exec(callback);
相关问题