coder14
coder14

Reputation: 223

Meteor return value as string

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

Upvotes: 1

Views: 350

Answers (2)

chridam
chridam

Reputation: 103345

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>

Upvotes: 1

Mariya James
Mariya James

Reputation: 985

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

Upvotes: 0

Related Questions