使用mongoose中有多級關(guān)聯(lián)情景,如
收藏 Collect中有圖片的ID關(guān)聯(lián)圖片Picture結(jié)合: {pictureId : {type: Schema.ObjectId, ref: 'Picture'}}
圖片Picture中有用戶ID管理: {userId : {type: Schema.ObjectId, ref: 'User'}}
用戶User: {name : {type: String}}
現(xiàn)在想獲取收藏列表的時候顯示圖片的用戶的名稱,就是User.name
3.8版本的mongoose的populate只能通過Collect獲取到Picture绸狐,而不能獲取到Picture的User
業(yè)績是說只能獲取的userId的值(用戶的ID,而不是對象)
4.5版本的mongoose支持deep-populate,也就是深度關(guān)聯(lián)獲取
可以嵌套populate獲取關(guān)聯(lián)對象的子關(guān)聯(lián)對象
var query = CollectModel.find({});
query.populate({
path:'pictureId',
populate:{path:'userId'} //嵌套populate
});
query.exec(function (err, docs) {
console.log(docs);
});
官方文檔:deep-populate