2014-02-06 50 views
15

有沒有辦法指示模型永遠填充某個字段?Mongoose.js:force始終填充

喜歡的東西,有 「場」 填充任何查找查詢:

{field: Schema.ObjectId, ref: 'Ref', populate: true} 

+1

雖然聽起來這將是一個非常有用的功能,我不知道你真的想在這個選項架構級別。通過應用此選項,您永遠無法獲取存儲在集合中的原始ObjectId,因此它會使更新和保存文檔變得困難。 –

+0

當您保存時,Mongoose足夠聰明,可以從填充的子對象中自動提取ObjectId。 –

回答

21

隨着貓鼬4.0,你可以以自動填充任何你想要使用查詢掛鉤。

以下示例來自Valeri Karpov的introduction document。架構的

定義:

var personSchema = new mongoose.Schema({ 
    name: String 
}); 

var bandSchema = new mongoose.Schema({ 
    name: String, 
    lead: { type: mongoose.Schema.Types.ObjectId, ref: 'person' } 
}); 

var Person = mongoose.model('person', personSchema, 'people'); 
var Band = mongoose.model('band', bandSchema, 'bands'); 

var axl = new Person({ name: 'Axl Rose' }); 
var gnr = new Band({ name: "Guns N' Roses", lead: axl._id }); 

查詢鉤來自動填充:

var autoPopulateLead = function(next) { 
    this.populate('lead'); 
    next(); 
}; 

bandSchema. 
    pre('findOne', autoPopulateLead). 
    pre('find', autoPopulateLead); 

var Band = mongoose.model('band', bandSchema, 'bands'); 
+0

非常好,謝謝 – webmaster

相關問題