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 回答