Mongoose .pre('save')没有触发 - bcrypt

时间:2018-03-15 14:34:31

标签: node.js mongodb mongoose

我一直在尝试创建一个简单的身份验证应用,但当我尝试在Mongodb中保存哈希密码时,面临着.pre('save')中间件无法触发的问题。 这是我的Model.js文件。

import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';

const userSchema = new mongoose.Schema({
  auth_method: {
    type: String,
    enum: ['local', 'google', 'facebook'],
    required: true
  },
  email: {
    type: String,
    lowercase: true,
    unique: true
  },
  local: {
    password: {
      type: String
    }
  },
  google: {
    id: {
      type: String
    }
  },
  facebook: {
    id: {
      type: String
    }
  }
},
  {
    collection: 'Users'
  });

const userModel = module.exports = mongoose.model('Users', userSchema);

userSchema.pre('save', function (next) {
  console.log("this:",this); //  Nothing prints to the console here
  if (this.auth_method !== 'local') {
    next();
  }
  bcrypt.genSalt(10, function (error, salt) {
    if (error) throw error;
    bcrypt.hash(this.local.password, salt, function (err, hashPassword) {
      if (err) throw err;
      else {
        this.local.password = hashPassword;
        next();
      }
    });
  });
});

const comparePassword = (candidatePassword, hashPassword) => {
  return new Promise((resolve, reject) => {
    bcrypt.compare(candidatePassword, hashPassword, (err, isMatch) => {
      if (err) reject(err);
      resolve(isMatch);
    });
  });
};

const saveUser = (user) => user.save();

const findUserByEmail = (email) => userModel.findOne({ email });

const findUserById = (id, cb) => { userModel.findById(id, cb); };

module.exports = {
  userModel,
  comparePassword,
  saveUser,
  findUserByEmail,
  findUserById
};

任何帮助表示赞赏,我已经尝试过在其他主题中建议的所有可能的解决方案,包括return next(this) 即使在数据库中,也没有local: {password: 'hashedPassword'}

的字段

1 个答案:

答案 0 :(得分:3)

您正在编译模型const userModel = module.exports = mongoose.model('Users', userSchema); 在创建userSchema.pre hook之前。

正确的顺序:

...
    userSchema.pre('save', function (next) {
      console.log("this:",this); //  Nothing prints to the console here
      if (this.auth_method !== 'local') {
        next();
      }
      bcrypt.genSalt(10, function (error, salt) {
        if (error) throw error;
        bcrypt.hash(this.local.password, salt, function (err, hashPassword) {
          if (err) throw err;
          else {
            this.local.password = hashPassword;
            next();
          }
        });
      });
    });
    const userModel = module.exports = mongoose.model('Users', userSchema);
...

请看这个简单的代码:http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt