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:プリフックが使用されていない場合は通常どおり保存されます。

最も参考になるコメント

ES6の太い矢印は、 thisを字句スコープthisが矢印関数の外側と同じであると言うための空想的な言い方です。 代わりにUser.pre('save', function(next) {});使用してください。

全てのコメント3件

ES6の太い矢印は、 thisを字句スコープthisが矢印関数の外側と同じであると言うための空想的な言い方です。 代わりにUser.pre('save', function(next) {});使用してください。

矢印関数でオブジェクトを取得する方法はありますか?「関数」を使用しますが、プロジェクトにはスタイルガイドが課されています。

残念ながらatmではありませんが、preフックは、パラメーターとしてではなく、 this介してドキュメントを渡すことに明示的に依存しています。 太い矢印はこのパラダイムでは機能しません。

このページは役に立ちましたか?
0 / 5 - 0 評価