I'm building an app using meteor.js and MongoDB and I have a question about cursor.forEach(). I want to check some conditions in the beginning of each forEach iteration and then skip the element if I don't have to do the operation on it so I can save some time.
Here is my code:
// 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();
}
});
I know I could turn cursor to array using cursor.find().fetch() and then use regular for-loop to iterate over elements and use continue and break normally but I'm interested if there is something similiar to use in forEach().
Each iteration of the forEach()
will call the function that you have supplied. To stop further processing within any given iteration (and continue with the next item) you just have to return
from the function at the appropriate point:
elementsCollection.forEach(function(element){
if (!element.shouldBeProcessed)
return; // stop processing this iteration
// This part will be avoided if not neccessary
doSomeLengthyOperation();
});