在mongoose模式预保存功能中使用异步调用

nov*_*von 4 mongoose node.js

我为我的架构设置了一个预保存功能,如下所示:

LocationSchema.pre('save', function(next) {
  geocoder.geocode(this.address, function ( err, data ) {
    if(data && data.status == 'OK'){
      //console.log(util.inspect(data.results[0].geometry.location.lng, false, null));

      this.lat = data.results[0].geometry.location.lat;
      this.lng = data.results[0].geometry.location.lng;
    }

    //even if geocoding did not succeed, proceed to saving this record
    next();
  });
});
Run Code Online (Sandbox Code Playgroud)

所以我想在实际保存模型之前对位置地址进行地理编码并填充lat和lng属性.在我上面发布的函数中,地理定位有效,但是this.lat和this.lng没有保存.我在这里错过了什么?

Joh*_*yHK 5

您正在geocoder.geocode回调中设置这些字段,因此this不再引用您的位置实例.

相反,做一些像:

LocationSchema.pre('save', function(next) {
  var doc = this;
  geocoder.geocode(this.address, function ( err, data ) {
    if(data && data.status == 'OK'){
      doc.lat = data.results[0].geometry.location.lat;
      doc.lng = data.results[0].geometry.location.lng;
    }
    next();
  });
});
Run Code Online (Sandbox Code Playgroud)