[英]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
集合上進行查找,該集合工作得很好,並返回兩個對象。 現在,我嘗試使用一個for循環,在“ Peligro”集合上進行查找,但它只是將一個對象返回到html模板。
html看起來像這樣:
{{#each listaPerfilUsuarioLikesPeligro}}
Nombre de Mascota {{metadata.tipoDeAnimalPeligro}}<br>
{{/each}}
第二個“ console.log”返回ID,他也創作了2次。
另外,如果我更改了for循環的return語句內的索引,它將返回數組中的第二個對象:
return Peligro.find({_id:findLike[1].postId}).fetch();
這是我的控制台的外觀:
ZW5TFWiAzCBgoTvn4
ethan
[FS.File]
MnEEb8bhaNFyLPhpe
ethan
[FS.File]
這是完成此任務的正確方法嗎?
您在for循環中有return
。 因此,您的助手當然不會返回findLike
每個對象的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;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.