Search code examples
meteoriron-router

Json page with collection data


i am very new to nodejs and meteor. i need to create a page content-type application/json and data from mongo collection. So when collection data change json page must be change.

For json page i use this example: https://stackoverflow.com/a/23666992/1446182

if (Meteor.isServer) {
  Meteor.startup(function () {

  try{
      var interval =  Meteor.setInterval(function() {
          var result = Meteor.http.call("GET", "http://192.168.2.144//ihale/meteorGetPage" );
          var resultJson = JSON.parse(result.content);
          var json = IhaleCollection.findOne();
          IhaleCollection.update(json, {$set: {json: resultJson}});
      }, 1000);
  }
  catch(err) {
      console.log(err);
  }
  });
     Router.map(function() {
     this.route('jsonExample', {
        where: 'server',
        path: '/json',
        action: function() {
            var obj = IhaleCollection.findOne();
            var headers = {'Content-type': 'application/json'};
            this.response.writeHead(200, headers);
            this.response.end(JSON.stringify(obj));
        }
    });
});
}

When Meteor.startup i start to update IhaleCollection every second. So how i can update json page when IhaleCollection change?


Solution

  • You can't. Not this way anyway. JSON has no builtin mechanism to detect if the source has changed and given that the router endpoint is outputting raw JSON data with no javascript, no automatic updates will happen. Only when a client refreshes the endpoint will there be an update.

    Meteor deals with reactive data by inserting javascript in the underlying html page. If you want to utilize that then you have to write a template, write a helper method to return JSON and use the helper method in the body.

    The helper method should look something like this:

    Template.jsondoc.helpers{(
      json: function(){
        return JSON.stringify(IhaleCollection.findOne());
      }
    })
    

    Template can be as simple as that:

    <template name="jsondoc">
      {{json}}
    </template>
    

    and your route will be as simple as this:

    Router.route('/jsondoc');