本文介绍了Meteor - 使用集合中的文档渲染模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我只是尝试使用 MongoDB find() 调用返回的文档的 result 属性来呈现模板.我开启了自动订阅.

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.

我有一个 html 模板

I have an html template

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

我正在尝试在 js 文件中呈现它:

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;
    }
}

mongo 中有一条记录 {type: "test", result: "success"}.代码不断抛出未定义没有属性结果"的错误.但是,当我只返回 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).

我唯一能想到的是它可能与meteor 的反应行为有关——也许MongoDB 调用最初返回undefined,然后更新以包含正确的文档.那是对的吗?如果是这样,我如何获得该文档的 result 属性的值?

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?

推荐答案

您的模板会在客户端启动后立即呈现,在服务器发送结果中的文档之前.试试这个(findOnefetch()[0] 的简写):

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;
}

这篇关于Meteor - 使用集合中的文档渲染模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 08:53