[英]Mongoose pre save is not running with discriminators
我試圖在將所有者保存在貓鼬之前調用pre save hook。 不調用預保存鈎子。 有什么辦法嗎?
const baseOptions = {
discriminatorKey: '__type',
collection: 'users'
}
const Base = mongoose.model('Base', new mongoose.Schema({}, baseOptions));
const Owner = Base.discriminator('Owner', new mongoose.Schema({
firstName: String,
email: String,
password: String,
}));
const Staff = Base.discriminator('Staff', new mongoose.Schema({
firstName: String,
}));
這不叫
Owner.schema.pre('save', function (next) {
if (!!this.password) {
// ecryption of password
} else {
next();
}
})
在編譯模型之前,需要將AFAIK掛鈎添加到架構中,因此這是行不通的。
但是,您可以先為鑒別器創建模式,然后定義鈎子,然后最后根據基本模型和模式創建鑒別器模型。 請注意,對於區分符掛鈎,也將調用基本架構掛鈎。
更多詳細信息在貓鼬文檔的此部分中:
對於您的情況,我相信這會起作用:
const baseOptions = {
discriminatorKey: '__type',
collection: 'users'
}
const Base = mongoose.model('Base', new mongoose.Schema({}, baseOptions));
// [added] create schema for the discriminator first
const OwnerSchema = new mongoose.Schema({
firstName: String,
email: String,
password: String,
});
// [moved here] define the pre save hook for the discriminator schema
OwnerSchema.pre('save', function (next) {
if (!!this.password) {
// ecryption of password
} else {
next();
}
})
// [modified] pass the discriminator schema created previously to create the discriminator "Model"
const Owner = Base.discriminator('Owner', OwnerSchema);
const Staff = Base.discriminator('Staff', new mongoose.Schema({
firstName: String,
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.