简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM