我正在尝试在 Mongoose 中保存所有者之前调用预保存 Hook 。不调用预保存 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 Hook 需要添加到您的模式之前编译您的模型,因此这是行不通的。
但是,您可以先为鉴别器创建模式,然后定义 Hook ,最后根据基本模型和模式创建鉴别器模型。 请注意,对于鉴别器 Hook ,基础架构 Hook 也将被调用。
更多细节在 mongoose 文档的这一部分:
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,
}));
关于javascript - Mongoose pre save 没有运行鉴别器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53758375/