填充猫鼬是什么意思?
问题描述:
我碰到下面的代码行,我听不懂,虽然有很多教程,让有关的populate
实例的信息却是没有解释究竟它means.Here是一个例子填充猫鼬是什么意思?
var mongoose = require('mongoose'), Schema = mongoose.Schema
var PersonSchema = new Schema({
name : String,
age : Number,
stories : [{ type: Schema.ObjectId, ref: 'Story' }]
});
var StorySchema = new Schema({
_creator : {
type: Schema.ObjectId,
ref: 'Person'
},
title : String,
fans : [{ type: Schema.ObjectId, ref: 'Person' }]
});
var Story = mongoose.model('Story', StorySchema);
var Person = mongoose.model('Person', PersonSchema);
Story.findOne({ title: /Nintendo/i }).populate('_creator') .exec(function (err, story) {
if (err) ..
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
})
答
populate()
函数是mongoose用于填充参考内的数据。在你的例子中,StorySchema
有_creator
字段,它将引用_id
字段,该字段基本上是mongodb文档的ObjectId
。
populate()函数可以接受一个字符串或一个对象作为输入。
其中字符串是需要填充的字段名称。你的情况是_creator
。猫鼬之后发现的一个文档从mongodb的和的结果是象下面这样
_creator: {
name: "SomeName",
age: SomeNumber,
stories: [Set Of ObjectIDs of documents in stories collection in mongodb]
},
title: "SomeTitle",
fans: [Set of ObjectIDs of documents in persons collection in mongodb]
填入也可以接受对象作为输入。
你可以在下面找到populate()
函数的文件。 http://mongoosejs.com/docs/2.7.x/docs/populate.html
你可以添加代码到你的问题? –
填充通常用于在查询http://mongoosejs.com/docs/2.7.x/docs/populate.html时填充ref对象属性 –