3

Mongoose モデルで保存前のコールバックをまとめようとしています。コールバックは、API に対して GET リクエストを行い、そのレスポンスをオブジェクトのフィールドに保存すると想定されています。node.js の性質上、非同期であり、リクエストが完了する前に保存が行われます。そのような操作を実行する正しい方法は何でしょうか?

現在、私は次のことを行っています。

Schema.pre('save', function(next){
  self = this
  request.get('myapi.com/method', { param_one: this_is_myparam } , function(err, data){
    self.myField = data['myFrield']
    self.save()
    next()
  }
  next()
})

私は正しいことをしていますか?それとも、JavaScript/Node のやり方がもっとありますか?

4

1 に答える 1

6

それは正しいように見えますが、self.save()行を削除すると、不要な重複保存が発生します。thisフック中に変更するだけpreSaveで、mongoose が mongodb への実際の保存を行います。

Schema.pre('save', function(next){
  //Yes, good. `this` here will be your mongoose model instance
  self = this
  request.get('myapi.com/method', { param_one: this_is_myparam } , function(err, data){
    //Yes, good. All you have to do here is CHANGE the mongoose model instance
    self.myField = data['myFrield']
    //No, bad. This is extraneous. By definition, mongoose is going to save your model
    //automatically after the "preSave" hook completes, so you should remove this.
    //self.save()
    next()
  }
  //No, bad. Remove this as well. You need to wait for the response to come back
  //next()
})
于 2013-06-16T14:58:09.187 に答える