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

时间:2013-06-16 14:17:27

标签: node.js express mongoose

我正在尝试在我的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方式吗?

1 个答案:

答案 0 :(得分:6)

看起来正确,但删除self.save()行,这将导致不必要的重复保存。您只需要在this挂钩期间修改preSave,然后猫鼬将为您实际保存到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()
})