简体   繁体   中英

Accessing mongodb collection in Meteor without a template

I have a collection with some data I brought from JSON file: Data.insert( JSON.parse(Assets.getText('data.json')) ); . I want to create a var with all the data in a JS file that is not part of a template.

Should I just do var data = Data.find({}).fetch()[0] ? Sometimes the fetch returns empty and I get undefined so I'm guessing this is not the best way. What would be the correct way?

Sounds like the data isn't always there at the time you call find (aside, you can use findOne ).

Based on your comments on the question sounds like maybe you want to put the function that calls find inside a Tracker.autorun() so that your variable updates as new data comes in. If that code is not in a template helper it won't get re run as the data comes in from the server. If something in your template depends on it then it may make sense to put it inside a helper in your template.

Alternately if the data won't change after server startup then you can use publish and subscribe mechanisms to declare your data ready() after it's loaded on the server, then do the client post processing in an onReady() callback in your subscribe() function, something like:

On the server:

Meteor.publish("startupData", function (){ 
    if (!this.userId) 
        return this.ready();
    else 
        return StartUpData.find({userId: this.userId});
}

On the client:

var startupData;
Meteor.subscribe("startupData", function(){
    var initStartupData = StartUpData.find({}) //will get all the published data for this user
    startupData = doPostProcessing(initStartupData)
}

Additionally, in the latter case (unchanging initial data), you'll want to make sure any template that depends on the data doesn't render until the data's arrived. I've handled this case in the past using IronRouter's waiton feature with something like this:

Router.route('/path', {
  name: "waiting_route_name",
  waitOn: function(){
    return Meteor.subscribe('yoursub', function post_process_onready(){
        //post processing here
    });
  },
  loadingTemplate: 'loading',
  action: function(){
    this.render("the_template_name")
  }
})

Having said that... If there's a template that depends on certain data, often that's a sign that the data should be either provided in a helper to that template or as the data context for the template. And Meteor will automatically handle re-rendering as that data arrives/changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM