无法使用mongoose将来自JSON的bcrypt哈希密码存储到mongodb中

时间:2017-09-10 11:49:11

标签: node.js express passport.js bcrypt

我无法使用mongoose将来自JSON的bcrypt哈希密码存储到mongodb中。我认为我的setPassword架构方法的实现存在错误。我用'crypto'实现替换了'bcrypt'并且它工作正常。散列字符串存储在数据库中。但是'bcrypt'无法做到这一点

我的model.js实现

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const Schema = mongoose.Schema;

// User Schema
const userSchema = new Schema({
  username: {
    type: String,
    index: true
  },
  password: {
    type: String
  },
  email: {
    type: String
  },
  name: {
    type: String
  }
});

userSchema.methods.setPassword =  function(password) {
  const saltRounds = 10;
  bcrypt.hash(password, saltRounds, function(err, hash) {
    this.password = hash;
  });
};

mongoose.model('User', userSchema);

我的路由器控制器实现

const passport = require('passport');
const mongoose = require('mongoose');
const User = mongoose.model('User');

const register = (req, res) => {

  const newUser = new User();

  newUser.name = req.body.name;
  newUser.email = req.body.email;
  newUser.username = req.body.username;
  newUser.setPassword(req.body.password);

  newUser.save((err) => {
    // Validations error
    if (err) {
      res.status(400).json(err);
      return;
    }

    res.status(200).json({
      success: true,
      message: 'Registration Successful'
    });

  });
};

1 个答案:

答案 0 :(得分:0)

this指向bcrypt.hash而非userSchema对象。

userSchema.methods.setPassword =  function(password) {
  const saltRounds = 10;
  var that = this;
  bcrypt.hash(password, saltRounds, function(err, hash) {
    that.password = hash;
  });
};

更新:使用回调或承诺

userSchema.methods.setPassword =  function(password, cb) {
  const saltRounds = 10;
  var that = this;
  bcrypt.hash(password, saltRounds, function(err, hash) {
    that.password = hash;
    cb();
  });
};

newUser.setPassword(req.body.password, function(){
    //Rest of code
});