Mongoose预保存没有与鉴别器一起运行



在mongose中保存所有者之前,我正在尝试调用预保存钩子。未调用预保存挂钩。有什么办法吗?

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钩子需要在编译模型之前添加到架构中,因此这将不起作用。

但是,您可以首先为鉴别器创建模式,然后定义钩子,最后根据基本Model和模式创建鉴别器Model。请注意,对于鉴别器挂钩,还会调用基本模式挂钩。

更多细节见猫鼬文档的这一部分:

MongooseJS鉴别器复制挂钩

对于您的情况,我相信这将起作用:

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

最新更新