我需要用Mongoose / Keystone填充两个级别,但是已经遇到了障碍。
我有3个型号:地区,国家和城市。 地区包含国家和国家/地区包含城市。
我的模特:
模特区域:
var Region = new keystone.List('Region');
Region.add({
name: {type: Types.Text}
, countries: {type: Types.Relationship, ref: 'Country', many: true}
});
模特国家
var Country = new keystone.List('Country');
Country.add({
name: {type: Types.Text}
, cities: {type: Types.Relationship, ref: 'City', many: true}
});
模范城市
var City = new keystone.List('City');
City.add({
name: {type: Types.Text}
});
查询:
keystone.list('Region').model.find()
.populate('countries')
.exec(function(err, regions){
console.log(regions)
});
收率:
{
name: 'Oceania',
countries: [
{
_id: 55d9b260415baa6958ac04c1
name: 'Australia',
cities: [
_id: 55d9b260415baa6958ac04c2,
_id: 55d9b260415baa6958ac04c3,
_id: 55d9b260415baa6958ac04c4
]
},
{
_id: 55d9b260415baa6958ac04c5
name: 'New Zealand',
cities: [
_id: 55d9b260415baa6958ac04c6,
_id: 55d9b260415baa6958ac04c7
]
}
]
},
{
name: 'Americas',
countries: [
{
_id: 55d9b260415baa6958ac04c1
name: 'USA',
cities: [
_id: 55d9b260415baa6958ac04d2,
_id: 55d9b260415baa6958ac04d3,
_id: 55d9b260415baa6958ac04d4
]
},
{
_id: 55d9b260415baa6958ac04c5
name: 'Canada',
cities: [
_id: 55d9b260415baa6958ac04e6,
_id: 55d9b260415baa6958ac04e7
]
}
]
}
]
我如何填充城市?据我所知,Mongoose不支持深度人口。
我可以查询结果或如何查询?
答案 0 :(得分:6)
在猫鼬中你可以这样做:
regionModel.find().populate("countries").exec(function(err, regions){
if(err){
throw err;
}
// Regions with populate countries
cityModel.populate(regions, {
path: 'countries.cities',
select: '_id name'
},function(err, regions) {
//Regions with Countries and Populated Cities
});
})
其实我不熟悉keystone语法,但我尝试将其转换为keystone语法。希望它有效,如果没有请尝试转换相当于keystonejs的上述代码
keystone.list('Region').model.find()
.populate('countries')
.exec(function(err, regions){
if(err){
throw err;
}
keystone.list('City').model.find()
.populate('cities')
.exec(function(err, regions){
console.log(regions)
});
});