Mongoose: 预保存钩子不提供文档

创建于 2015-09-02  ·  3评论  ·  资料来源: Automattic/mongoose

预保存挂钩存在问题,其中 'this' 应该给我正在保存的文档,但它却给了 undefined。

import mongo from 'mongoose'
import crypt from 'bcryptjs'

const User = new mongo.Schema({
  username: {type: String, unique: true, required: true},
  password: {type: String, select: false, required: true}
  // token: {type: String}
})
//
User.pre('save', (next) => {
  console.log(this);
  if (this.isModified('password') || this.isNew) {
    crypt.genSalt(10, (err, salt) => {
      if (err) {
        next(err)
      } else {
        crypt.hash(user.password, salt, (err, hash) => {
          if (err) {
            next(err)
          } else {
            user.password = hash
            next()
          }
        })
      }
    })
  } else {
    next()
  }
})

export default mongo.model('User', User)

可能是什么错误?
PS:不使用pre hook时正常保存。

最有用的评论

ES6 中的胖箭头将this绑定到词法作用域,这只是一种奇特的说法,即箭头函数内部的this与箭头函数外部的相同。 请改用User.pre('save', function(next) {});

所有3条评论

ES6 中的胖箭头将this绑定到词法作用域,这只是一种奇特的说法,即箭头函数内部的this与箭头函数外部的相同。 请改用User.pre('save', function(next) {});

有没有办法用箭头函数获取对象?,我会使用“函数”,但在项目中强加了样式指南。

不幸的是不是 atm,预挂钩明确地依赖于通过this而不是作为参数传递文档。 粗箭头不适用于这种范式。

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

dmmalam picture dmmalam  ·  93评论

ChrisZieba picture ChrisZieba  ·  76评论

cosminn777 picture cosminn777  ·  158评论

saudelog picture saudelog  ·  79评论

aartiles picture aartiles  ·  47评论