3

我有一个预保存挂钩来加密模式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 文件导入我的数据库。

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

4

1 回答 1

5

您可以使用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'
});
于 2016-03-22T12:51:41.627 回答