【问题标题】:Mongoose pre save is not running with discriminatorsMongoose 预保存未使用鉴别器运行
【发布时间】:2019-01-24 05:52:48
【问题描述】:

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

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

【问题讨论】:

    标签: javascript node.js mongoose discriminator


    【解决方案1】:

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

    【讨论】:

    • 这对我有用。在编译模型之前,需要将 AFAIK 挂钩添加到架构中。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 2016-02-01
    • 2021-04-15
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多