gpt4 book ai didi

javascript - Mongoose .js : force always populate

转载 作者:IT老高 更新时间:2023-10-28 13:04:40 25 4
gpt4 key购买 nike

有没有办法指示模型总是填充某个字段?

类似于在任何查找查询中填充“字段”:

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

?

最佳答案

在 Mongoose 4.0 中,您可以使用查询 Hook 来自动填充您想要的任何内容。

以下示例来自 introduction document瓦莱里·卡尔波夫(Valeri Karpov)。

模式定义:

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 });

查询 Hook 以自动填充:

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

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

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

关于javascript - Mongoose .js : force always populate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21592351/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com