有条件地跳过猫鼬钩子函数 [英] Conditionally skip mongoose hook function

查看:35
本文介绍了有条件地跳过猫鼬钩子函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a pre-save hook to encrypt password field of User schema, like:

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

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

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

By this way, I have encrypted password string in my database every time a User created or updated.

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

Now I have a JSON file of old User data with the encrypted password. I want to use this User model to import the JSON file into my database.

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

How can avoid the pre-save hook to encrypt the password again?

推荐答案

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

You can use User.collection.insert() to bypass all Mongoose validations (the type of the inserted data won't be checked) and hooks, it uses the MongoDB driver directly:

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

这篇关于有条件地跳过猫鼬钩子函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆