我有一个预先保存的钩子来加密 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' });更多推荐
有条件地跳过猫鼬钩子函数
发布评论