我试图在将所有者保存在猫鼬之前调用pre save钩子。不调用预保存钩子。有什么办法吗?
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();
}
})
答案 0 :(得分:0)
在编译模型之前,需要先 将AFAIK挂钩添加到您的架构中,因此这将无法正常工作。
但是,您可以先为鉴别器创建模式,然后定义钩子,然后最后根据基本模型和模式创建鉴别器模型。 请注意,对于区分符挂钩,也会调用基本架构挂钩。
猫鼬文档的这一部分提供了更多详细信息:
MongooseJS Discriminators Copy Hooks
对于您的情况,我相信这会起作用:
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,
}));