在mongoose.js上保存挂钩之前使用的正确方法

Got*_*osh 3 mongoose node.js express

我正试图在我的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()
})
Run Code Online (Sandbox Code Playgroud)

我做对了吗?或者有更多的JavaScript/Node方式吗?

Pet*_*ons 6

看起来正确,但删除该self.save()行,这将导致不必要的重复保存.你只需要thispreSave钩子中修改然后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()
})
Run Code Online (Sandbox Code Playgroud)