使用嵌套的“”循环迭代流星中的集合;forEach”;

iterate over a collection in meteor using nested loop of " forEach "

本文关键字:forEach 集合 流星 循环 嵌套 迭代      更新时间:2023-09-26

我将从我想要得到的结果的小描述开始:

假设我们有一个名为"Elements"的集合,其中包含4个文档:"a"、"b"、"c"answers"d"。我想迭代"Elements",并在名为"Queries的新集合中插入对:

(a,b);(a,c);(a,d);(b,a);(b,c)。。。(d,a);(d,b);(d,c)=>这意味着"查询"将在末尾包含(在本例中)4*3=12对元素(文档)。

以下是我正在使用的代码(这是流星服务器中的一种方法,由点击按钮触发):

'Queries': function() {
    var allElements = Elements.find();
    allElements.forEach(function(myLeftElement){ //First forEach
        allElements.forEach(function(myRightElement){// Nested forEach
            if(myLeftElement._id !== myRightElement._id){
                Queries.insert( {myLeftElement : myLeftElement._id, myRightElement : myRightElement._id} );
            }
        }); //End Of nested forEach
    }); //End Of First forEach
}

事实上,它只适用于第一个"myLeftElement"和所有其他元素"myRightElement",但仅限于此:它在"Queries"集合中插入对:[(a,b);(a,c)和(a,d)],然后停止。

由于我是一个网络开发的初学者,尤其是在使用Meteor时,我正在寻求你的帮助。

1) 我需要理解为什么嵌套的游标方法"forEach"一旦停止,整个函数就会停止。

2) 如何改进代码以获得我真正想要的结果:对于我的集合"myLeftElement"的每个元素,都有一个forEach方法,它可以与所有其他元素"myRightElement"创建对。然后移动到下一个"myLeftElement",并执行相同操作直到结束。

谢谢,

下面是一个使用普通JavaScript在数组上迭代的工作示例,可以得到预期的结果:

var elements = ['a', 'b', 'c', 'd'];
var result = [];
elements.forEach(function(item) {
  // Create a copy of the current array to work with
  var elements_copy = elements.slice(0);
  var temp_array = [];
  /*
  Delete the current `item` from the array since
  we don't want duplicate 'a:a' items in the array.
  IMPORTANT: There are better ways of doing this,
  see: http://stackoverflow.com/questions/3954438/remove-item-from-array-by-value
  */
  elements_copy.splice(elements_copy.indexOf(item), 1);
  elements_copy.forEach(function(child_item) {
    temp_array.push(item + "," + child_item);
  });
  result.push(temp_array);
});
console.log(result);

您需要确保在开发人员工具中打开控制台才能查看结果。

当你刚开始的时候,我建议你使用最不复杂的工作场景——比如这里我把Meteor和Mongo从图片中删除了——以确保你的逻辑是正确的,然后再在其他场景中工作。

因此,直接回答您的问题:

  1. 不确定它为什么会停止,因为我无法重建
  2. 提供的示例应该足够了——但我相信还有更好的方法

希望能有所帮助!

@chysicaljoy的回答在两个方面激励了我:

  • 使用数组
  • 以及删除数组中重复的"a:a"项的更好方法(通过访问他提供的链接)

非常感谢。

现在,在进行了必要的修改后,这里有一个使用Meteor和Mongodb代码实际上可以很好地工作的解决方案:

'Queries' : function() {
var allElements = Elements.find().map(function(item){return item._id} ); /* this returns an array of item._id of all elements*/
var totalItems = allElements.length;
var itemsCounter = 0;
var withoutLeftItem;
   while(itemsCounter < totalItems){
      withoutLeftItem=_.without(allElements,allElements[itemsCounter] ); /*The function _.without(array, *items) used in underscore.js returns array with specified items removed */    
      withoutLeftItem.forEach(function(myRightElement){
         Queries.insert( {myLeftElement : allElements[itemsCounter], myRightElement : myRightElement} );
      });
   itemsCounter++;
   }
 }

我仍然很想知道为什么问题中提出的解决方案没有按预期工作,也很想看看在内存使用方面优化的代码。

希望这能帮助其他人。感谢所有