mongodbmeteorhandlebars.jsmeteorite

Loop over the Mongodb objects to get the values in Meteorjs


I am first Time working With Meteorjs and MongoDB. I am working on a Q&A application. where I have a list of objects which i got using Meteor database call. I want to looper over the list and want to split one of its attribute to the length 50 and then want to send a list of these splitted objects to the database.what I have is this

Template.questions.questions = function () {
questions= Meteor.questions.find({topic_id: Session.get("currentTopicId")});
return questions
}
Every question object in the questions list has an attribute question_text. Using loop i want to split this attribute to length of fifty and then want to push that to an empty list and return that list . Like
questions_list=[]
for(i=0;i<questions.length;i++){
    question=questions[i].question_text[0:50]   // python syntex to get first 50 char of a string
    questions_list.push(question
}
return questions_list

and My HTML is like

<tbody>
            {{#each questions}}
            <tr>
                <td class="span2" style="overflow:hidden;width:50px">
                    <a href="#" data-id="{{_id}}" class="edit"> {{question_text}}</a>
                </td>

            </tr>

            {{/each}}

            </tbody>

suggest me guys how can i acieve this in meteorjs. my problem is when i try to loop over this questions list there are many attributes like Collection, Results, Queries. here i am unable to iterate this list of objects.

In the same way how can i get the error message thrown back by meteorjs


Solution

  • This will give you list of shortened texts of all questions matching a query:

    var questions = Questions.find({...}).map(function(question) {
        return question.text.substr(0,50);
    });
    

    You could use it directly in a helper:

    Template.questions.questions = function () {
        return Questions.find({...}).map(function(question) {
            return question.text.substr(0,50);
        });
    };
    

     


     

    By the way, Questions.find({...}) does not return a list of questions, but a cursor object that you can use to manipulate query data in an effective way (like that map method above). To get raw array, you need to use fetch on that cursor: Questions.find({...}).fetch().