in my web-app, some "news-and-events-entries" have cover-images, some don't (images are stored with CollectionFS). Here's an example with an image (key is coverImageId):
JSON:
{
"_id" : "gDPwfDJFxh3y7NBBK",
"title" : "EGOS 2015 reminder: Open Organizations for an Open Society?",
"description" : "\n\t\t \t\t\n\t\t \t\tOpen Organizations for an Open Society? Practicing Openness in Innovation, Strategy and Beyond; Convenors: Leonhard Dobusch, Freie Universität Berlin, Georg von Krogh, ETH Zurich, Switzerland, Richard Whittington, Oxford University, Link to website: : http://bit.ly/EGOS15Open\n\t\t \t\n\t\t \t",
"type" : "news",
"createdAt" : ISODate("2016-02-28T20:30:09.316Z"),
"coverImageId" : "teEfXMANGbSn4vWkD"
}
Template:
<div class="row text-left">
{{#each newsEventsData}}
<div class="col-sm-4">
<div class="caption">
{{#if imageExists}}
<h4>TRUE {{title}}<img alt="news thumbnail" class="news-thumbnail" src="{{ coverImage.url }}" /></h4>
{{else}}
<h4>FALSE {{title}}</h4>
{{/if}}
<p class="text-muted">{{{description}}} <a href="{{pathFor route = 'newsAndEventsPage'}}" class="textlink">read more </a></p>
</div>
</div>
{{/each}}
</div> <!-- ROW -->
If there's an image, the image is shown. So, this works. However, the else
part never gets rendered. I assume my helper renders true because it's enough if one document contains a coverImageId
.
Helper:
Template.allNewsEvents.helpers({
newsEventsData: function () {
if(Session.equals("newsEventsSeeMore","no")) {
return NewsEvents.find({type: { $in: Session.get('newsEventsViewMain')}}, {sort: {createdAt: -1}, limit: 3});
}
else {
return NewsEvents.find({type: { $in: Session.get('newsEventsViewMain')}}, {sort: {createdAt: -1}});
}
},
imageExists: function () {
return NewsEvents.find({_id:this._id},{coverImageId: { $exists: true } });
}
});
Any help really appreciated.
find
returns a cursor, which is an object and will always evaluate to true. You want:
imageExists: function () {
var event = NewsEvents.findOne( {_id:this._id} );
if( event && event.coverImageId ) {
return true;
} else {
return false;
}
}