Mongoose: 不是函数错误 - this.isModified 不是函数

创建于 2016-09-18  ·  11评论  ·  资料来源: Automattic/mongoose

当我使用以下代码时:

userSchema.pre('save', (done) => {
  if(this.isModified('password')) {
    bcrypt.hash(this.password, null, null, (err, hash) => {
      if(err) return next(err);

      this.password = hash;
      this.updated_at = new Date().toISOString();
      done();
    });
  } else {
    return done();
  }
});

我收到以下错误:

TypeError: this.isModified is not a function
    at model.userSchema.pre (C:\code\project\core\models\user.js:26:11)
    at _next (C:\code\project\node_modules\hooks-fixed\hooks.js:62:30)
    at fnWrapper (C:\code\project\node_modules\hooks-fixed\hooks.js:186:8)
    at model.Object.defineProperty.value.fn (C:\code\project\node_modules\mongoose\lib\schema.js:221:11)
    at _next (C:\code\project\node_modules\hooks-fixed\hooks.js:62:30)
    at fnWrapper (C:\code\project\node_modules\hooks-fixed\hooks.js:186:8)
    at C:\code\project\node_modules\mongoose\lib\schema.js:196:17
    at C:\code\project\node_modules\kareem\index.js:127:16
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

问题:

  • this不是文档、查询或模式。 它的价值是{}

我该如何解决?

最有用的评论

您正在为回调使用箭头运算符,这会更改this 。 如果你定义一个常规回调你应该没问题,例如:

userSchema.pre('save',  function(done)  {
});

所有11条评论

您正在为回调使用箭头运算符,这会更改this 。 如果你定义一个常规回调你应该没问题,例如:

userSchema.pre('save',  function(done)  {
});

行。 谢谢。 有用。

修复你的 eslintrc

2016 年 11 月 29 日星期二上午 5:16,Nick Rameau通知@ github.com
写道:

有没有办法用箭头功能做到这一点? 我正在使用 ES6 和我的
eslintrc 抱怨定期回调。


您收到此消息是因为您订阅了此线程。
直接回复此邮件,在 GitHub 上查看
https://github.com/Automattic/mongoose/issues/4537#issuecomment-263567210
或使线程静音
https://github.com/notifications/unsubscribe-auth/ABi5KbZG27HnF2sX2RwDIhTp4Rz1lIG_ks5rDCW1gaJpZM4J_8-c
.

我也有这个问题。 感谢@VictorGerritsenQLVR 的帮助!

有没有办法更改代码以适应箭头运算符,而不是使用function(next)

@domarp-j 好问题。 我想了想并试图弄清楚,但我想不出比切换到常规回调函数更简单的方法了。 也许其他人已经做到了。 我会密切关注这个问题。

没办法,胖箭头使用上下文的词汇范围,没有办法绕过它。

有同样的问题,谢谢帮助

嗨,在 es6 箭头功能上遇到了同样的问题。 非常感谢你!

太好了,谢谢你

谢谢,对我也有用。

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