update surrounding statement illegal for javascript mongodb foreach meteor

javascript - surrounding - mongodb foreach update



"Continuar" en cursor.forEach() (2)

Cada iteración de forEach() llamará a la función que ha proporcionado. Para detener el procesamiento posterior dentro de cualquier iteración dada (y continuar con el siguiente elemento) solo tiene que return de la función en el punto apropiado:

elementsCollection.forEach(function(element){ if (!element.shouldBeProcessed) return; // stop processing this iteration // This part will be avoided if not neccessary doSomeLengthyOperation(); });

Estoy construyendo una aplicación usando meteor.js y MongoDB y tengo una pregunta sobre cursor.forEach (). Quiero verificar algunas condiciones al principio de cada una para cada iteración y luego omitir el elemento si no tengo que hacer la operación en él para poder ahorrar algo de tiempo.

Aquí está mi código:

// Fetch all objects in SomeElements collection var elementsCollection = SomeElements.find(); elementsCollection.forEach(function(element){ if (element.shouldBeProcessed == false){ // Here I would like to continue to the next element if this one // doesn''t have to be processed }else{ // This part should be avoided if not neccessary doSomeLengthyOperation(); } });

Sé que podría convertir el cursor en una matriz usando cursor.find (). Fetch () y luego usar for-loop para iterar sobre los elementos y usar continue y break normalmente, pero me interesa si hay algo similar para usar en forEach ( )


En mi opinión, el mejor enfoque para lograr esto es usar el method filter ya que no tiene sentido volver en un bloque para cada uno; para un ejemplo en tu fragmento:

// Fetch all objects in SomeElements collection var elementsCollection = SomeElements.find(); elementsCollection .filter(function(element) { return element.shouldBeProcessed; }) .forEach(function(element){ doSomeLengthyOperation(); });

Esto reducirá su filtred elementos y solo conservará los elementos filtred que deberían procesarse.