Mongoose pre save is not running with discriminators Mongoose pre save is not running with discriminators mongoose mongoose

Mongoose pre save is not running with discriminators


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 firstconst OwnerSchema = new mongoose.Schema({    firstName: String,    email: String,    password: String,});// [moved here] define the pre save hook for the discriminator schemaOwnerSchema.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,     }));