node.js - 在 Mongoose 模式预保存功能中使用异步调用

标签 node.js mongoose

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

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();
  });
});

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

最佳答案

您在 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();
  });
});

关于node.js - 在 Mongoose 模式预保存功能中使用异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22079399/

相关文章:

node.js - 如何在 Ubuntu 15.10 上通过命令安装 nodejs

javascript - 在 Node.js 中,setTimeout 可靠吗?

node.js - grpc 错误 SSL23_GET_SERVER_HELLO

node.js - Mongoose: ref 自定义字段名称

javascript - Mongoose.Find() 与数组和 OR 运算符

javascript - Firebase 函数 Express : How to get URL params with paths

xml - NodeJS xpath 库是否支持 XPath 查询表达式?

javascript - 从 Mongoose 帖子 findOneAndUpdate Hook 更新

javascript - 使用 Mongoose 保存多个文档并在保存最后一个文档时执行某些操作

node.js - Mongoose:一系列自定义实例