Javascript 在Schema.pre中传递值(';更新';)

Javascript 在Schema.pre中传递值(';更新';),javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我的更新功能是 User.update({_id: data._id}, {$set: {password: req.body.newpassword}}) .then(data => { res.json(data) }) .catch(err => { res.status(400).json(err); }); 我的pre中间件定义为 UserSchema.pre('up

我的更新功能是

 User.update({_id: data._id}, {$set: {password: req.body.newpassword}})
        .then(data => {
          res.json(data)
        })
        .catch(err => {
          res.status(400).json(err);
        });
我的
pre
中间件定义为

UserSchema.pre('update',function (next) {

 console.log(this.password)  //it shows undefined

});
我不知道如何使用它,以便在
pre
中间件中传递我的
password
字段,我想进一步对其进行散列


thanx.

您可以为此使用node.js
加密模块

var crypto = require('crypto');

var UserSchema = new mongoose.Schema({ password: 'string' });

UserSchema.pre('update',(next) => {
    this.password = crypto.createHash('md5').update(this.password).digest('hex');
    next();
});

var User = mongoose.model('User', UserSchema);
User.update({_id: data._id}, {$set: {password: req.body.newpassword}})
    .then(data => {
      res.json(data)
    })
    .catch(err => {
      res.status(400).json(err);
    });

但是它将
this.password
显示为“undefined”,您在
.update(this.password)
中写入它。在创建新模型之前,您需要定义模式挂钩@鲁珀什:请您解释一下如何创建该模式挂钩。但当我使用
UserSchema.pre('save')
时,前面的方法非常有效。