Ok so I'm playing with meteorJS and I'm using a yahoo finance service to fetch some data in json format using jquery. Once I receive the data I want to store it into my mongo DB. The code I have for the purpose is as follows
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);
}
});
}
}
});
now as you can see I have no clue if what I'm doing is correct or not. I know you can insert into mongo db with a json structure which is what I have but not sure if this is the right way or not. Any help is much appreciated.
You're almost there, just going about it a little backwards. You should check if it's the server first then fetch the data. Also you should use Meteor's built in http methods.
First you need to add the http package. In your meteor project's root directory run this from a terminal:
meteor add http
Then the related code is:
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)
});
}
});
}
Docs for Meteor's http methods:
http://docs.meteor.com/#meteor_http
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With