首页 > 解决方案 > 在 findOneAndUpdate 中生成散列密码

问题描述

这是我对 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();
});

我想在用户更新详细信息时创建一个散列密码

标签: node.jsmongodbmongoose

解决方案


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

推荐阅读