Ethaan
Ethaan

Reputation: 11376

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

I have this 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();
      }
  }
});

So here first I'm doing a find on my LikesPost Collection, which works pretty fine, and returns two objects. Now I try to use a for loop, to do a find on the `Peligro' collection but it's just returning one object to the html template.

The html looks like this:

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

The 2nd `console.log' returns the ids and he author 2 times too.

Also if I change the index inside the return statement on the for loop it returns the second object in the array:

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

This is how my console looks:

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

This is the correct way to accomplish this?

Upvotes: 0

Views: 617

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21364

You have a return in your for loop. So of course your helper won't return the results for each of the objects in findLike, but just the first.

Maybe this is what you want?

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

Upvotes: 1

Related Questions