Node.JS Schema.pre('save)不会更改数据 [英] Node.JS Schema.pre('save) is not changing data

查看:182
本文介绍了Node.JS Schema.pre('save)不会更改数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm making user authorization system and want to hash password before save it to DB. To reach this i use bcrypt-nodejs. The question in title above;

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

推荐答案

针对您的问题的解决方案如下:

Below the solution for your problem:

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

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

Code that I used to run the solution:

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

您的第一个问题是您不能在这种方法中使用箭头功能:

Your first problem is that you can not use arrow function in this type of method: Same Error Solved

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

Second problem, is that you need to call the bcrypt.hashSync method, if you don‘t want to handle Promises.

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

And one observation about your schema, all the fields are unique. This attribute unique:true will create a index in the database, and you won't find the user by password. Here the moongose documentation: Moogose Documentation

对于初学者来说,常见的陷阱是模式的唯一选项不是验证器.它是构建MongoDB唯一索引的便捷助手.有关更多信息,请参见FAQ.

A common gotcha for beginners is that the unique option for schemas is not a validator. It's a convenient helper for building MongoDB unique indexes. See the FAQ for more information.

这篇关于Node.JS Schema.pre('save)不会更改数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆