Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if mongo document field exists

I want to check if the field "imageUrl" are inserted from a form into a MongoDb collection.

If it has a value, I want to return the URL, else return false. I'm not used to Mongo, and wonder how I can achieve this. Not every entry have a imageUrl field, but some do. So I need to check if it even exists for every document.

Here's my helper, where I want to have the logic:

Template.CatchesList.helpers({
  catches: function () {
    return Catches.find({}, {sort: {date: -1}});
  },

  image: function() {
    if (this.imageURL) // Need proper logic here
      return true;
    else
      return false;
  }
});

And in my template:

{{#if image}}
    <td><img width="100" src="{{imageUrl}}"></td>
{{/if}}
like image 292
Filip Blaauw Avatar asked Dec 01 '25 00:12

Filip Blaauw


1 Answers

MongoDB has the $exists operator to filter results where the property does not exist in the document. So you can change your query to:

return Catches.find({ "imageUrl": { "$exists": true }}, { "sort": { "date": -1 }});

And then only items that have the property will be returned.

If you are only talking about templates, then a simple conditional test on the field returns logically where it is present or not present:

{{#each catches}}
    {{> catch }}
{{/each}}

Then:

<template name="catch">
    <tr>
        <!-- other fields -->
        <td>{{#if imageUrl}}<img width="100" src="{{imageUrl}}">{{/if}}</td>
    </tr>
</template>

Where only the logic contained within {{#if}}{{/if}} will actually render.

like image 77
Blakes Seven Avatar answered Dec 03 '25 22:12

Blakes Seven