在服务器上运行函数后插入新集合

Insert new collection after function runs on server

当我 return 来自谷歌的地理编码 API 我试图将它保存到我的数据库中。我一直在尝试使用下面的代码,只是插入一个没有运气的测试文档。我认为这与 meteor 是异步的有关。如果我 运行 在 googleMapsClient.geocode 函数之前插入函数,它工作正常。有人可以告诉我我做错了什么。

Meteor.methods({
  'myTestFunction'() {
    googleMapsClient.geocode({
      address: 'test address'
    }, function(err, response) {
      if (!err) {
        Test.insert({test: 'test name'});
      }
    });
}
});

您应该 运行 在客户端使用 googleMapsClient.geocode() 函数,在服务器端使用 Test.insert() 函数(通过方法)。试试这个:

服务器端

Meteor.methods({
  'insertIntoTest'(json) {
    Test.insert({results: json.results});
  }
});

客户端

googleMapsClient.geocode({
  address: 'test address'
}, function(err, response) {
  if (!err) {
    Meteor.call('insertIntoTest', response.json);
  }
});

Meteor Methods 应该在 serverclient 两边都可用。因此,请确保您的方法可由服务器访问;通过在 /server/main.jsfolder structuring 上正确导入。 (如果一个方法在服务器上包含一个秘密逻辑 运行,那么它应该与服务器和客户端上的方法 运行 隔离开来)

我现在明白你是从哪里想到 运行 客户端的 NPM 库的,但这不是你真正想要的。当您 运行 您在此处提供给我们的初始代码段时,您应该会在 meteor 实例的服务器端遇到一些错误。问题是 google npm 库 运行s 在它自己的线程中,这阻止了我们使用 Meteor 的方法。您可以做的最简单的事情是用 Meteor.wrapAsync 包装函数,所以它看起来像这样。

try {
  var wrappedGeocode = Meteor.wrapAsync(googleMapsClient.geocode);
  var results = wrappedGeocode({ address : "testAddress" });
  console.log("results ", results);
  Test.insert({ test : results });
} catch (err) {
  throw new Meteor.Error('error code', 'error message');
}

您可以通过 looking at this thread 找到更多信息,还有其他人也在处理同样的问题