最近好忙啊,好久沒有來寫博客了~
乾巴蝶!
還是那句話,寫一遍真的比看一遍要好很多!
populate方法提供外鍵填充的功能。由於Mongoose是極具JavaScript特點的程序庫,提供了極其簡單和強大的填充功能,因此,populate不止可以填充單個文檔,也支持多文檔,甚至直接填充對象!
外鍵引用
在定義Schema字段時,可以添加ref屬性來指向另一個Schema。 該ref屬性在此後被填充(populate)時將被mongoose讀取。
例子:
const DetailSchema = new Schema({
userId: {
type: ObjectId,
required: true,
ref: 'user' // 關聯
}
})
填充外鍵
Detail.findOne({title: 'yy'})
.populate('user')
.exec(function(err, detail){
if(err) throw err;
console.log(detail.user.name);
});
只填充指定字段
Story.findOne({title: 'xx'})
.populate('creator', 'name') // 只返回Person的name字段
.exec(function(err, story){
if(err) throw err;
console.log(story.creator.name);
});
填充多個屬性
鏈式調用即可
Story.find(...)
.populate('creator fans')
.exec();
Story.find(...)
.populate('creator')
.populate('fans')
.exec();
填充限制
在執行填充命令的同時,還可以指定過濾器以及限制大小,方法就是將方法的參數換成一個對象:
Story.find(...)
.populate({
path: 'fans',
match: { age: { $gte: 21 }},
select: 'name',
options: { limit: 5 }
});
.exec();
這段代碼的結果只會得到:年齡大於21的對象,並且只返回name字段,最多返回5個。
多級關聯填充
填充引用的引用。
var userSchema = new Schema({
name: String,
friends: [{ type: ObjectId, ref: 'User' }]
});
User.
findOne({ name: 'Val' }).
populate({
path: 'friends',
populate: { path: 'friends' }
});