更新猫鼬模型(node.js)中的一个字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27157163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:09:33  来源:igfitidea点击:

Update one field in mongoose model (node.js)

node.jsmongodbmongoose

提问by user1930848

I have a user schema where I want to update some info, like this.

我有一个用户架构,我想在其中更新一些信息,就像这样。

User.findOne({_id: idd}, function(err, usr){
   usr.info = "some new info";
   usr.save(function(err) {
   });
});

But the model has a hook on save to hash the password

但是模型有一个钩子保存来散列密码

UserSchema.pre('save', function(next) {
    if (this.password && this.password.length > 6) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }

    next();
});

Now when I try to save it takes the allready hased password and hash it again, any idea how to avoid this?

现在,当我尝试保存它时,需要使用已有的密码并再次对其进行哈希处理,知道如何避免这种情况吗?

回答by BatScream

Use Model.Updateand move the creation of a new password to an independent function.

使用Model.Update并将新密码的创建移至独立函数。

var salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');;
var newPassword = this.hashPassword("someNew password");
User.update({_id: idd}, {
    info: "some new info", 
    password: newPassword
}, function(err, affected, resp) {
   console.log(resp);
})

回答by Thomas Decaux

Did you try to use isModified?

你试过用isModified吗?

UserSchema.pre('save', function(next) {
    if (this.password && this.password.length > 6 && MYMODEL.isModified('password')) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }

    next();
});