有条件地跳过mongoose hook功能

时间:2016-03-22 12:07:14

标签: node.js mongodb mongoose mongoose-schema

我有一个预保存挂钩来加密password架构的User字段,例如:

var schema = new mongoose.Schema({
    username: 'string',
    password: 'string'
});

schema.pre('save', encrptPasswordHook);
schema.pre('update', encrptPasswordHook);
schema.pre('findOneAndUpdate', encrptPasswordHook);
...

通过这种方式,每次User创建或更新时,我都会在我的数据库中加密密码字符串。

现在我有一个带有加密密码的旧User数据的JSON文件。我想使用此User模型将JSON文件导入我的数据库。

如何避免预保存挂钩再次加密密码?

1 个答案:

答案 0 :(得分:3)

您可以使用User.collection.insert()绕过所有Mongoose验证(无法检查插入数据的类型)和挂钩,它直接使用MongoDB驱动程序:

var UserSchema = new mongoose.Schema({
    username: 'string',
    password: 'string'
});

var User = mongoose.model('User', UserSchema);

User.collection.insert({
    username: 'Some Name',
    password: 'The Encrypted Password'
});