Javascript 密码不存在';t在保存到数据库之前进行散列

Javascript 密码不存在';t在保存到数据库之前进行散列,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我正在使用Node.js、Mongoose、MongoDb、Express开发一个应用程序 我试图在用户注册时将密码保存到数据库中之前对其进行散列,但它似乎不起作用。密码保存时没有散列,有什么建议吗 'use strict' let mongoose = require('mongoose') let bcrypt = require('bcrypt-nodejs') var Schema = mongoose.Schema var userSchema = Schem

我正在使用Node.js、Mongoose、MongoDb、Express开发一个应用程序

我试图在用户注册时将密码保存到数据库中之前对其进行散列,但它似乎不起作用。密码保存时没有散列,有什么建议吗

'use strict'

  let mongoose = require('mongoose')
  let bcrypt = require('bcrypt-nodejs')
   var Schema = mongoose.Schema

    var userSchema = Schema({
     name: { type: String, required: true, unique: true },
     password: { type: String, required: true },
     createdAt: {
     type: Date,
     require: true,
     default: Date.now
    }
   })
   // check if user already exists
   userSchema.path('name').validate(function (name) {
   User.findOne({name}, function (err, user) {
  if (err) {
  console.log('error')
  } if (user) {
  console.log('The user already exists')
    console.log(user)
  }
  })
}, 'The user already exists')

  // password validation

userSchema.path('password').validate(function (password) {
 return password.length >= 6
 }, 'The password must be of minimum length 6 characters.')
var User = mongoose.model('User', userSchema)

 // hashing and adding salt pre save()

   userSchema.pre('save', function (next) {
    bcrypt.genSalt(10, function (err, salt) {
    if (err) {
     return next(err)
     }
    bcrypt.hash(this.password, salt, null, function (err, hash) {
     // Store hash in your password DB.
    if (err) {
      return next(err)
    }
       // set the password to the hash
      this.password = hash
    })
    next()
 })
 })
  module.exports = User

这是因为在调用
bcrypt.hash
回调之前执行
next()
。将
next()
移动到
bcrypt.hash
回调中

 userSchema.pre('save', function(next) {

    bcrypt.genSalt(10, function(err, salt) {

        if (err) {
            return next(err)
        }

        bcrypt.hash(this.password, salt, null, function(err, hash) {
            // Store hash in your password DB.
            if (err) {
                return next(err)
            }
            // set the password to the hash
            this.password = hash
            next()
        })

    })
})
使用回调时,应在
bcrypt.hash()
方法中调用
next()

对于同步:

userSchema.pre('save', (next) => {
   const salt = bcrypt.genSaltSync(10)
   const hash = bcrypt.hashSync(this.password, salt)

   this.password = hash
   next()
})

我搬走了,什么都没发生!我还有别的事要做吗?可能需要在server.js中使用它吗?是的,请尝试移动
var User=mongoose.model('User',userSchema)
正上方
module.exports=User
和下方
userSchema.pre(…