在 Helper 函数中使用 for 循环的正确方法 |流星

Correct way to use for loop inside a Helper function | MeteorJS

我有这个helper function

Template.myTemplate.helpers({
listaPerfilUsuarioLikesPeligro:function(){   
    var findLike = LikesPost.find({authorId:Meteor.userId()}).fetch(); 
     for(var i = 0;i<findLike.length;i++){
           console.log(findLike[i].postId)
           console.log(findLike[i].author)
           var findLook = Peligro.find({_id:findLike[i].postId}).fetch();
           console.log(findLook)
           return Peligro.find({_id:findLike[i].postId}).fetch();
      }
  }
});

所以我首先在我的 LikesPost Collection 上进行查找,效果很好,return 有两个 object。现在我尝试使用 for 循环,在 `Peligro' collection 上进行查找,但它只是 returning 一个 object 到 html 模板。

html 看起来像这样:

{{#each listaPerfilUsuarioLikesPeligro}}
  Nombre de Mascota {{metadata.tipoDeAnimalPeligro}}<br>
{{/each}}

第二个“console.log”return是 id,他也是作者 2 次。

此外,如果我在 for 循环中更改 return 语句内的索引,它 return 是数组中的第二个 object:

return Peligro.find({_id:findLike[1].postId}).fetch();

这是我的控制台的样子:

ZW5TFWiAzCBgoTvn4
 ethan
[FS.File]
MnEEb8bhaNFyLPhpe
 ethan
[FS.File]

这是完成此任务的正确方法吗?

您的 for 循环中有一个 return。因此,您的助手当然不会 return findLike 中每个对象的结果,而只是第一个。

也许这就是你想要的?

Template.myTemplate.helpers({                                                   
    listaPerfilUsuarioLikesPeligro:function(){                                  
        var findLike = LikesPost.find({authorId:Meteor.userId()}).fetch();      
        var rtv = [];                                                           
        for(var i = 0;i<findLike.length;i++){                                   
            console.log(findLike[i].postId)                                     
            console.log(findLike[i].author)                                     
            var findLook = Peligro.find({_id:findLike[i].postId}).fetch();      
            console.log(findLook)                                               
            rtv = rtv.concat(Peligro.find({_id:findLike[i].postId}).fetch());   
        }                                                                       
        return rtv;                                                             
    }                                                                           
});