Meteor - rendering template with a document from a Collection

╄→гoц情女王★ 提交于 2020-01-04 13:37:58

问题


Basically, I'm just trying to render a template with the result attribute of a document returned by a MongoDB find() call. I have autosubscribe on.

I have an html template

<template name="results">
    status: {{result}}
</template>

And I'm trying to render it in the js file:

if (Meteor.is_client) {
    Template.results.result = function() {
        return Results.find({'type': 'test'}).fetch()[0].result;
    }
}

There's a record in mongo {type: "test", result: "success"}. The code keeps throwing an error that "undefined has no attribute result". However, when I just return Results.find({'type': 'test'}).fetch()[0] it does actually return an object, not undefined (and if I log it to the console, I can see that it does have the result attribute I set).

The only thing I can think of is that it might be related to the reactive behavior of meteor - maybe the MongoDB call is initially returning undefined, and then later updating to contain the correct document. Is that correct? And if so, how can I get the value of the result attribute of that document?


回答1:


Your template gets rendered as soon as the client starts up, before the server has sent the documents in Results. Try this (findOne is shorthand for fetch()[0]):

Template.results.result = function() {
    var obj = Results.findOne({'type' : 'test'});
    return obj && obj.result;
}


来源:https://stackoverflow.com/questions/10167464/meteor-rendering-template-with-a-document-from-a-collection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!