用meteorJS中的服务数据填充mongodb

cli*_*oid 4 jquery mongodb meteor

好的,我正在玩meteorJS,我正在使用雅虎金融服务,使用jquery以json格式获取一些数据.收到数据后,我想将其存储到我的mongo DB中.我为此目的的代码如下

Stocks = new Meteor.Collection("stocks");
$.ajax({
  type:'GET',
  url:'http://query.yahooapis.com/v1/public/yql?q=select*from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22GOOG%22)&env=store://datatables.org/alltableswithkeys&format=json',
  success:function(data){
    if (Meteor.is_server) {
          Meteor.startup(function () {
            if (Stocks.find().count() === 0) {
                Stocks.insert(data);
            }
          });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

现在,你可以看到我不知道我在做什么是正确的.我知道你可以插入带有json结构的mongo db,这是我所拥有但不确定这是否正确.任何帮助深表感谢.

gre*_*reg 9

你几乎就在那里,只是向后走一点.您应该首先检查它是否是服务器,然后获取数据.你也应该使用Meteor的内置http方法.

首先,您需要添加http包.在你的meteor项目的根目录中从终端运行:

meteor add http

那么相关的代码是:

if(Meteor.is_server){
  Meteor.startup(function () {
    if(Stocks.find().count() === 0){
      var url = "http://query.yahooapis.com/v1/public/yql" + 
                "?q=select*from%20yahoo.finance.quotes%20where" +
                "%20symbol%20in%20%28%22GOOG%22%29&env=" +
                "store://datatables.org/alltableswithkeys&format=json"
      Meteor.http.get(url, function(error,results){
        var stock_data = JSON.parse(results.content).query.results.quote
        Stocks.insert(stock_data)
      });
    }
  });
}
Run Code Online (Sandbox Code Playgroud)


Docs for Meteor的http方法:http: //docs.meteor.com/#meteor_http