javascript - Meteor js cursor hasNext() and next()? -
problem
i have potentially big find query has stop once server "javascript" conditions met, instance server have documents results figure out solution.
the idea here iterate cursor mongo, hitting mongo "on demand", kinda "streaming", neither server or mongo has fetch results @ once.
expected behaviour
- query , cursor ( r = collection.find() )
- check next ( r.hasnext() )
- fetch next ( r.next() )
- once requirements met, stop ( delete r )
example code
collection.find().foreach(function(doc) { doc = do_my_business( doc ); if (doc.found) { // hey mister cursor, go home , die! don't touch mongo anymore! return false; } });
the real problem
i created question how end here: https://stackoverflow.com/questions/30836586/mongodb-find-near-until-maxdistance-or-at-least-x-records
a meteor cursor isn't mongo cursor. meteor cursors don't have hasnext or next. so, question foreach
, same es5 foreach
. here's can do:
1.fetch docs array & run loop on it, break when criteria met.
2.turn flag when criteria met & check @ beginning of function:
if (ishappy) return; doc = do_my_business( doc ); if (doc.found) ishappy = true;
3. use 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 foreach garbage & use $where
findone
+ (do find().limit(1).explain()
can see won't touch every document.)
5.store in database don't have use javascript on cursor. repeating javascript loop on every doc on server should avoided plague. storage cheap. processing, not much.
Comments
Post a Comment