Meteor return value as string

送分小仙女□ 提交于 2019-12-24 12:30:47

问题


This is what I want to achieve. I got two collections: Questions and Answers. When a user answers a question, the answer will set in the Answers collection, and it passes the ID of the question with it.

I'm displaying a list with all the questions using this helper:

questions: function (){
    return Question.find({});
}

And this html:

<ol>
    {{#each questions}}
        <li>{{question}}</li>
    {{/each}}
</ol>

I want to display the answers that every user gave, below each question. I want to return the Question's ID as a string value, so I can do something like:

answers:function(){
    return Answer.find({question: <The ID of the question>});
}

Can anyone help me with this?

Yours, L


回答1:


Supposing your Question collection has the following schema (simplified for brevity):

QuestionSchema = new SimpleSchema({
    title: {
        type: String,
        label: "Question"
    },
    category: {
        type: String,
        label: "Category"
    }
});

and your Answer collection has

AnswerSchema = new SimpleSchema({
    text: {
        type: String,
        label: "Question"
    },
    author: {
        type: String,
        label: "Author"
    }
    question: {
        type: String,
        label: "Question"
    }
});

You can go about this by creating two template helpers where the first just returns an array of question documents and the second takes a single question id as parameter and returns a cursor of all of the answers with that question id:

Template.questions.helpers({
    questions: function(){        
        return Question.find({}).fetch();
    },
    answers: function(questionId){
        return Answer.find({question: questionId}).fetch();
    }
});

Next the template needs nested {{#each}} blocks with the first one iterating over the questions array and passing the answers to the next each as the parameter of the next helper.

<template name="questions">
    {{#each questions}}
        <h1>{{this.title}}</h1>
        <ol>
        {{#each answers this._id}}
            <li>{{text}}</li>
        {{/each}}
        </ol>
    {{/each}}
</template>



回答2:


Try with this code. Hope it works

<ol>
{{#each questions}}
    <li>{{question}}</li>
    <li>{{answers}}</li>
{{/each}}
</ol>

In your js file.

answers:function(){
 id = this._id
return Answer.find({question:id});
}

According to your response from function you can use either with or each



来源:https://stackoverflow.com/questions/33649529/meteor-return-value-as-string

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