How do I determine if a Mongo query returned no matches? [SOLVED]


#1

I’m sure this has been asked before, but I can’t seem to find an answer for this.

TL;DR
How do I determine if a Mongo query returned no matches? I would expect to look for something like ‘null’, ‘undefined’, or ‘false’ but none of those appear to work. It also appears that what is returned in the Mongo console is not the same as what is returned in the client console.

The issue
I want my template helper to return false if no matches were found for a query. (So I can display a message like “Sorry, no matches were found.”) However, it seems that while in the meteor mongo console “nothing” is returned…

…Meteor returns an undefined collection on the client side.

Either way it is not clear to me how, in a template helper, to detect if a query returned no matches, something that I am guessing should be straightforward.

My Template Helper

Template.tags_list.helpers({
  myTags: function() {
    var my_tags = Tags.find({ "authors.authorId": Meteor.userId() });
    console.log(my_tags);

    if(my_tags == null) {
      return false;         
    } else {
      return my_tags;
    }
  }
});

#2

Add .fetch() and it’ll turn your cursor into an actual array of items. This is one of the issues lots of people are stumbling over initially. find() returns a cursor, while findOne an actual element. Cursor.fetch() gets the underlying elements.


#3

You can check your data in template

<template name="tags_list">
    {{#if myTags.count}}
      {{#each myTags}}
      {{/each}}
    {{else}}
      There are no tags.
    {{/if}}
</template>

And simply return cursor in

Template.tags_list.helpers({
  myTags: function() {
    return Tags.find({ "authors.authorId": Meteor.userId() });
  }
});

#4

Great, thanks! I knew it would be something simple.


#5

hi, can i check retrieved data count into Meteor.publish()?