简体   繁体   中英

Having troubles with getting data from Meteor collection

Can someone explain this thing to me: if I'm getting data from a collection in browser's console, it works fine, but at the same time when a template (which uses the same collection) is being rendered it throws an exception as the query result is empty. What am I doing wrong?

Hubs = new Meteor.Collection("hubs");
Meteor.subscribe("hubs");
Template.thread.posts = function() {
    var hubName = 'foo',
        thread = Session.get("currentThread"),
        hub = Hubs.find({ name: hubName }).fetch()[0];
//throws: "Uncaught TypeError: Cannot read property 'threads' of undefined "
    return hub.threads[thread].posts;
}

//this being executed in browser's console yeilds an object:
Hubs.find({name: 'foo'}).fetch()[0]

Other templates that use the same collection work fine, though

When Meteor initially loads on the browser it wont yet have the data from the collections from the server.

It takes a very short amount of time for them to be available. So you just need to handle the case where there is no result provided. When the data arrives reactivity should update all your templates with the new data.

You can use something like:

hub = Hubs.findOne({ name: hubName })
if(hub) return hub.threads[thread].posts;

findOne is a shorter version of find().fetch[0] . So if there isn't a result ie null nothing is returned and .threads wont be read so there wouldn't be an exception.

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