javascript - Mongoose pre save 没有运行鉴别器

标签 javascript node.js mongoose discriminator

我正在尝试在 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/

相关文章:

javascript - 尝试链接我的 array.js 文件时出现 404 错误

javascript - 通过 ref 或 prop 更改 React 中的子组件?

node.js - 如何访问 Node 模块文档 - eslint

node.js - aws lambda 调用未在 POST 上填充正文

javascript - 使用 Mongoose 将数组( 'tags')保存到 MongoDB

javascript - Bootstrap 验证冲突

javascript - socket.io 错误 undefined is not a function

javascript - 如何使用条件参数查询 mongodb 中的多个文档

javascript - 错误 [ERR_HTTP_HEADERS_SENT] : Cannot set headers after they are sent to the client in Node JS

javascript - 如何强制下载未使用的 CSS 图像?