在Meteor中的Collection中定义值数组

时间:2015-07-21 19:38:37

标签: javascript meteor

我在我的应用程序中定义了以下Collection:

Projects = new Mongo.Collection("projects")

在这个Collection中,我插入了:

Projects.insert({
    source: "https://upload.wikimedia.org/wikipedia/commons/7/7f/Pug_portrait.jpg",
    title: "pug",
    artist: "pug",
    description: "This piece shows the duality of pug",
    price: "priceless"
});

Projects.insert({
    source: "http://i.stack.imgur.com/D2ABD.gif",
    title: "doge",
    artist: "doge",
    description: "much doge, many deal with it, wow",
    price: "bout tree fiddy"
})

我正在尝试使用以下辅助函数创建图像源的数组:

sourceArray : function () {
          // returns array of sources
          var sources = [];
          for (var i = 0; i < Projects.find().count(); i++) {
            sources.push(images[i].source);
          }
          return sources;

      }

“图像变量先前定义为:images = Projects.find().fetch();

然后我在HTML中调用辅助函数。

<p>{{sourceArray}}</p>

在页面上,第一个来源短暂出现,但在几秒钟内消失。在浏览器控制台中,显示以下内容:

meteor.js:888 Exception in template helper: TypeError: Cannot read property 'source' of undefined
    at Object.Template.body.helpers.sourceArray (http://localhost:3000/art.js?913b8578eb54cde21abc07c994f6b29267232bc5:61:28)
    at http://localhost:3000/packages/blaze.js?a5c324925e5f6e800a4c618d71caf2848b53bf51:2880:16
    at http://localhost:3000/packages/blaze.js?a5c324925e5f6e800a4c618d71caf2848b53bf51:1651:16
    at http://localhost:3000/packages/blaze.js?a5c324925e5f6e800a4c618d71caf2848b53bf51:2928:66
    at Function.Template._withTemplateInstanceFunc (http://localhost:3000/packages/blaze.js?a5c324925e5f6e800a4c618d71caf2848b53bf51:3476:12)
    at http://localhost:3000/packages/blaze.js?a5c324925e5f6e800a4c618d71caf2848b53bf51:2927:27
    at Spacebars.call (http://localhost:3000/packages/spacebars.js?7bafbe05ec09b6bbb6a3b276537e4995ab298a2f:172:18)
    at Spacebars.mustacheImpl (http://localhost:3000/packages/spacebars.js?7bafbe05ec09b6bbb6a3b276537e4995ab298a2f:109:25)
    at Object.Spacebars.mustache (http://localhost:3000/packages/spacebars.js?7bafbe05ec09b6bbb6a3b276537e4995ab298a2f:113:39)
    at null._render (http://localhost:3000/template.art.js?30aa5e2d0b6d3de2f69b7341296ae51b8ce737ba:27:22)

异常是指这行代码:

sources.push(images[i].source);

如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

尝试:

sourceArray : function () {
      var images = Projects.find().fetch();

      var sources = [];
      for (var i = 0; i < images.length; i++) {
        sources.push(images[i].source);
      }
      return sources;

  }

如果您说,您将图像定义为模板助手属性,则可能需要

this.images[i].source

答案 1 :(得分:1)

只需在帮助器中重新定义它。这可能是你想要的,所以它会被动反应。这是一个应该有效的实现:

sourceArray: function() {
  return _.pluck(Projects.find().fetch(), 'source');
}