有没有办法指示模型永远填充某个字段?Mongoose.js:force始终填充
喜欢的东西,有 “场” 填充任何查找查询:
{field: Schema.ObjectId, ref: 'Ref', populate: true}
?
有没有办法指示模型永远填充某个字段?Mongoose.js:force始终填充
喜欢的东西,有 “场” 填充任何查找查询:
{field: Schema.ObjectId, ref: 'Ref', populate: true}
?
随着猫鼬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');
非常好,谢谢 – webmaster
这个插件是你的问题的解决方案:
虽然听起来这将是一个非常有用的功能,我不知道你真的想在这个选项架构级别。通过应用此选项,您永远无法获取存储在集合中的原始ObjectId,因此它会使更新和保存文档变得困难。 –
当您保存时,Mongoose足够聪明,可以从填充的子对象中自动提取ObjectId。 –