简体   繁体   中英

Mongoose pre save is not running with discriminators

I am trying to call pre save hook before saving owner in mongoose. Pre save hook is not called. Is there any way to do it ?

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

this is not called

 Owner.schema.pre('save', function (next) {
    if (!!this.password) {
        // ecryption of password
    } else {
        next();
    }
})

AFAIK hooks need to be added to your schema before compiling your model, hence this won't work.

You can, however, first create the schema for the discriminator, then define the hook(s), and then finally create the discriminator Model from the base Model and schema. Note that, for discriminator hooks, the base schema hooks will be called as well.

More details are in this section of mongoose docs:

MongooseJS Discriminators Copy Hooks

For your case, I believe this will work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM