Meteor:模板始终返回true

时间:2016-03-02 19:04:30

标签: mongodb templates meteor handlebars.js collectionfs

在我的网络应用程序中,一些“新闻和事件条目”有封面图像,有些则没有(图像存储在CollectionFS中)。这是一个图像示例(键是 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"
}

模板:

<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 --> 

如果有图像,则显示图像。所以,这很有效。但是,else部分永远不会被渲染。我假设我的助手渲染为真,因为如果一个文档包含coverImageId就足够了。

助手:

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 } });
  }
}); 

任何帮助都非常感激。

1 个答案:

答案 0 :(得分:1)

find返回一个光标,它是一个对象,并且总是计算为true。你想要:

  imageExists: function () {
    var event = NewsEvents.findOne( {_id:this._id} );
    if( event && event.coverImageId ) {
      return true;
    } else {
      return false;
    }
  }