user1487244
user1487244

Reputation: 121

Meteor Helpers - a function to check if document exists

The following code works as intended, ie the helper returns true if there is a document and false if there is no document. However, i am getiing a warning on my console.

"Error: Exception in template helper: TypeError: Cannot read property 'filepickerId' of undefined at Object.Template.navigation.helpers.ichk..."

The warning is inconsistent and not sure why that i the case. Once again, the code however works without any flow that i can tell.

Template.nav.helpers({

        'ichk': function(){

            var ct= Info.findOne({_id:Meteor.userId()});

            if (ct.profilepic.filepickerId) {
                return true;
            }else{
                return false;
            }

Upvotes: 0

Views: 200

Answers (2)

David Weldon
David Weldon

Reputation: 64342

You need a guard. Your helper can be rewritten like this:

Template.nav.helpers({
  ichk: function () {
    var ct = Info.findOne({ _id: Meteor.userId() });
    return !!(ct && ct.profilepic && ct.profilepic.filepickerId);
  }
}

Upvotes: 2

Lazov
Lazov

Reputation: 1476

If it works you should add one more line in order to get rid of the exception.

Template.nav.helpers({

       'ichk': function(){

        var ct= Info.findOne({_id:Meteor.userId()});

                if(ct){

                if (ct.profilepic.filepickerId) {

                return true;

                 }

                else{

                return false;

                }}

In this way you first check if the document exists.

Upvotes: 1

Related Questions