Meteor: Underscore _findWhere iteration through loop objects only works in chrome console, in app it says undefined

拥有回忆 提交于 2019-12-13 06:11:00

问题


I'm trying to fetch an object 'single Post' within an object 'Posts' from a json file within meteor, which looks like this.

I found an effective way of doing it, using underscore findWhere to get to it. this is the code

_.findWhere(_.findWhere(CategoryCollection.find().fetch(),
{"_id":"CategoryPublication-5"}).posts,{"ID":46});

however when i put this into meteor, i'm getting undefined

this is the code i used

 Template.CategoryArticleSingle.helpers({
          articles: function () {
            var id = FlowRouter.getParam('ID')
            var category = FlowRouter.getParam('category')
            console.log(CategoryCollection.find().fetch());
                 let match = _.findWhere(_.findWhere(CategoryCollection.find().fetch(), {"_id":category}).posts,{"ID": id});
            console.log("match",id,category,match);
            return match;
          }
        });

Why am i getting undefined

update.

would this be correct? i substituted the 47 id, with just id so i can use it for any link.

Im getting "category" is read-only error.

Template.CategoryArticleSingle.helpers({
          articles: function () {
            var id = FlowRouter.getParam('ID')
            var category = FlowRouter.getParam('category')
            console.log(CategoryCollection.find().fetch());
            const category = CategoryCollection.find().fetch().find(c => c._id === id);
            let post = null;

            if (category) {
              post = category.posts.find(p => p.ID === id);
            }
            console.log("post",id,category,post);
            return post;
          }
        });

回答1:


There's no need to use lodash/underscore's findWhere. This functionality is built into ES2015. Also, you may consider breaking up the code into a few lines to make it more legible.

const category = CategoryCollection.find().fetch().find(c => c._id === 'CategoryPublication-5');
let post = null;

if (category) {
  post = category.posts.find(p => p.ID === 47);
}


来源:https://stackoverflow.com/questions/37931938/meteor-underscore-findwhere-iteration-through-loop-objects-only-works-in-chrom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!