【问题标题】:Meteor retrieving sub-array data from MongoDBMeteor 从 MongoDB 检索子数组数据
【发布时间】:2016-12-05 15:12:27
【问题描述】:

这似乎是一个相当常见的问题。但是它没有返回官方答案(或者我的词汇量太少了,我找不到它)或者我没有得到建议的答案。

这是对 MongoDB 记录的子数组的基本迭代,我目前正在使用的记录是一个名为 questions 的集合,带有单个记录:

{ 
    "_id" : ObjectId("1"), 
    "question" : "question 1", 
    "answers" : { 
        "answer1" : "answer 1", 
        "answer2" : "answer 2" 
    } 
}

我的助手如下:

Template.testquiz.helpers({
    questions: function() {
       return questions.find({});
    },
});

那么我们就有钱了:

<template name="testquiz">
    {{#each questions}}
        {{question}}
        <br /><br />
        {{#each answers}}
            {{this}}
        {{/each}}
    {{/each}}
</template>

我可以让问题出现,但是我尝试在对象“answers”上运行嵌套 each 的所有变体都会导致错误:this.answers, answers this, questions.answers, pull the nested每个进入它自己的模板并调用它,等等。持续一个小时。我的直觉是,这是标准功能,我从一开始就忽略了一些事实。

我们总是很感激答案,但如果这很简单,只需将我指向文档,我会查找它。

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    你没有一个数组,你有一个子对象。对象不是可迭代的,除非你让帮助者来做到这一点。

    你应该改变:

    { 
        "_id" : ObjectId("1"), 
        "question" : "question 1", 
        "answers" : { 
            "answer1" : "answer 1", 
            "answer2" : "answer 2" 
        } 
    }
    

    到:

    { 
        "_id" : ObjectId("1"), 
        "question" : "question 1", 
        "answers" : [ 
            "answer 1", 
            "answer 2" 
        ] 
    }
    

    那么你的模板就可以工作了。

    【讨论】:

    • 谢谢您,先生。我会去阅读差异。感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2020-09-18
    • 1970-01-01
    • 2016-12-29
    • 2019-03-20
    • 1970-01-01
    相关资源
    最近更新 更多