【问题标题】:Node.JS Schema.pre('save) is not changing dataNode.JS Schema.pre('save) 没有改变数据
【发布时间】:2018-12-19 20:35:36
【问题描述】:

我正在制作用户授权系统,并希望在将密码保存到数据库之前对其进行哈希处理。为此,我使用 bcrypt-nodejs。 上面标题中的问题;

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');

var userSchema = new mongoose.Schema({
    email: { 
         type: String,
         unique: true,
         required: true,
    },
    username: {
         type: String,
         unique: true,
         required: true
    },
    password: { 
         type: String,
         unique: true,
         required: true
    }
});

userSchema.pre('save', (next) => {
    var user = this;
    bcrypt.hash(user.password, bcrypt.genSaltSync(10), null, (err, hash) => {
        if (err) {
            return next(err);
        }
        user.password = hash;
        next();
    })
});

module.exports = mongoose.model('User', userSchema);

【问题讨论】:

    标签: javascript node.js asp.net-web-api web bcrypt


    【解决方案1】:

    下面是您问题的解决方案:

    var mongoose = require('mongoose');
    var bcrypt = require('bcrypt-nodejs');
    
    var userSchema = new mongoose.Schema({
      email: {
        type: String,
        unique:true,
        required: true
      },
      username: {
        type: String,
        required: true
      },
      password: {
        type: String,
        required: true
      }
    });
    
    userSchema.pre('save', function() {
      console.log(this.password);
      this.password = bcrypt.hashSync(this.password);
      console.log(this.password);
    });
    
    module.exports = mongoose.model('User', userSchema);
    

    我用来运行解决方案的代码:

    exports.create = async function () {
      let user = new User({
        email : 'test@test.com',
        username: 'new username',
        password: '123abc'
      });
    
      return await user.save()
        .then((result) => {
          console.log(result);
        }).catch((err) => {
          console.log(err)
        });
    };
    

    你的第一个问题是你不能在这种方法中使用箭头函数Same Error Solved

    第二个问题,如果你不想处理 Promises,你需要调用 bcrypt.hashSync 方法。

    关于您的架构的一项观察是,所有字段都是唯一的。这个属性unique:true会在数据库中创建一个索引,你不会通过密码找到用户。这里是月光文档:Moogose Documentation

    初学者的一个常见问题是模式的唯一选项不是验证器。它是构建 MongoDB 唯一索引的便捷助手。有关详细信息,请参阅常见问题解答。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多