Meteor js cursor hasNext() and next()?

problem

I have a potentially big find query which has to stop once my server "javascript" conditions are met, for instance my server already have documents results to figure out a solution.



The idea here is to iterate a cursor from mongo, hitting mongo "on demand", kinda "streaming", so neither my server or mongo has to fetch all results at once.



expected behaviour


query and get cursor ( r = Collection.find() )
check for next ( r.hasNext() )
fetch next ( r.next() )
once my requirements are met, stop ( delete r )


example code

Collection.find().forEach(function(doc) {
doc = do_my_business( doc );
if (doc.found) {
// hey mister cursor, go home and die! don't touch my mongo anymore!
return false;
}
});


the real problem

I created another Question which is actually how i end up here:
Mongodb find near until $maxDistance or at least X records?



Answers

A meteor cursor isn't a mongo cursor. Meteor cursors don't have hasNext or next. So, this is really just a question about forEach, which is the same as the ES5 forEach. So here's what you can do:



1.Fetch all the docs into an array & run a for loop over it, break when criteria is met.



2.Turn a flag when the criteria is met & check at the beginning of the function:



if (isHappy) return;
doc = do_my_business( doc );
if (doc.found) isHappy = true;


3. Use a try catch loop:



foo = {};
try {
Collection.find().forEach(function(doc) {
doc = do_my_business( doc );
if (doc.found) {
throw foo;
}
});
} catch(e) {
if (e !== foo) {
throw e;
}
}


4.Forget the forEach garbage & use a $where with a findOne + (do a find().limit(1).explain() so you can see that it won't touch every document.)



5.Store something in your database so you don't have to use javascript on the cursor. Repeating a javascript loop over every doc on the server should be avoided like the plague. Storage is cheap. processing, not so much.