在findOneAndUpdate中生成哈希密码

时间:2018-06-28 11:31:19

标签: node.js mongodb mongoose

这是我对findOneAndUpdate的查询

  const { email, password, id } = req.body
  Artist.findOneAndUpdate({ _id: id }, { $set: req.body }).then((artist) => {
      return res.json({
        success: true,
        message: "Invitation sent."
      });
  })

这是我的模式

var artistSchema = new mongoose.Schema({
  name: { type: String, default: '' },
  password: { type: String, default: '' }
})
artistSchema.pre('findOneAndUpdate', function (next) {
    console.log('------------->>>>>> findOneAndUpdate: ');
    console.log(this.password) // why undefined?
    next();
});

我想在用户更新详细信息时创建哈希密码

3 个答案:

答案 0 :(得分:2)

const { email, password, id } = req.body;
Artist.findByIdAndUpdate(id, { $set: req.body }).then(artist => {
  return res.json({
    success: true,
    message: "Invitation sent."
  });
});

bcrypt示例

var artistSchema = new mongoose.Schema({
  name: { type: String, default: "" },
  password: { type: String, default: "" }
});
artistSchema.pre("update", function(next) {
  bcrypt.hash(this.password, 10, function(err, hash) {
    if (err) return next(err);
    this.password = hash;
    next();
  });
});

答案 1 :(得分:0)

let crypto = require('crypto');
let mongoose = require('../mongoose'),
    Schema = mongoose.Schema;

然后是架构

let schema = new Schema({
    name: { 
        type: String, 
        default: '' 
    },
    hashedPassword: {
        type: String,
        required: true
    },
    salt: {
        type: String,
        required: true
    }
});

然后是方法和虚函数

schema.methods.encryptPassword = function(password){
    return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
};

schema.virtual('password').set(function(password){
    this._plainPassword = password;
    this.salt = Math.random() + '';
    this.hashedPassword = this.encryptPassword(password);
}).get(function(){ return this._plainPassword; });

您可以像这样检查密码

schema.methods.checkPassword = function(password){
    return this.encryptPassword(password) === this.hashedPassword;
};

导出模块

module.exports.Artist = mongoose.model('Artist', schema);

然后像以前一样保存

const { email, password, id } = req.body;
Artist.findOneAndUpdate({ _id: id }, { $set: req.body }).then((artist) => {
  return res.json({
    success: true,
    message: "Invitation sent."
  });
});

但是我建议您也使用静态。例如:

schema.statics.updateUser = function (data){
    // your code
}

然后您可以使用

Artist.updateUser(req.body).then((res) => {
    // response
})

答案 2 :(得分:0)

答案:写console.log(JSON.stringify(this._update));

我的检查空白密码的解决方案。

userSchema.pre('findOneAndUpdate', function() {
    console.log(JSON.stringify(this._update));
    if (this._update.password.length == 0) {
        this._update = {
            "fullname": this._update.fullname
        };
    }
    else {
        this._update = {
            "fullname": this._update.fullname,
            "password": bcrypt.hashSync(this._update.password, bcrypt.genSaltSync(8), null)
        };
    }
});
相关问题