Le Qs
Le Qs

Reputation: 805

Fetching data inside a template's event handler

I want to test a few things that regards some data I have stored stored in a collection called exams. This is my code

Template.Examinations.events({
  'click .reactive-table tr': function() {
    Session.set('selectedPersonId', this._id); 
    var cursor = Exam.findOne(Session.get("selectedPersonId"));
    if (!cursor.count()) return;
      cursor.forEach(function(doc){
      console.log(doc._id);
    });    
  },
});

Every time I run the code by clicking a row, I get the error

Uncaught TypeError: cursor.count is not a function

Why am I getting this error?

Update

{
    "_id" : "RLvWTcsrbRXJeTqdB",
    "examschoolid" : "5FF2JRddZdtTHuwkx",
    "examsubjects" : [
        {
            "subject" : "Z4eLrwGwqG4pw4HKX"
        },
        {
            "subject" : "fFcWby8ArpboizcT9"
        }
    ],
    "examay" : "NrsP4srFGfkc5cJkz",
    "examterm" : "5A5dNTgAkdRr5j53j",
    "examclass" : "gYF2wE4wBCRy9a3ZC",
    "examname" : "First",
    "examdate" : ISODate("2016-05-07T22:41:00Z"),
    "examresultsstatus" : "notreleased"
}

Upvotes: 0

Views: 71

Answers (1)

Sudheer Jami
Sudheer Jami

Reputation: 757

You are using Exam.findOne which will return an object but not array, which is causing the error cursor.count is not a function. You should use Exam.find({}).fetch() and then you can get the count form the result.

Template.Examinations.events({
  'click .reactive-table tr': function() {
    Session.set('selectedPersonId', this._id); 
    var examsArray = Exam.find({ personId: this._id}).fetch();
    examsArray.forEach(function(doc){
      console.log(doc._id);
    });
  },
});

Upvotes: 1

Related Questions