最近好忙啊,好久没有来写博客了~
干巴蝶!
还是那句话,写一遍真的比看一遍要好很多!
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' }
});