peter.petrov
peter.petrov

Reputation: 39457

MongoDB - Inconsistent cursor behavior

Could anyone explain this?

    [test] 2014-01-31 18:40:36.243 >>> var rowNEW = db.people.find( { "name" : "joe", "age" : 20} );
    [test] 2014-01-31 18:40:42.853 >>> rowNEW.forEach(function() { print ('FOUND ROW'); } );
    FOUND ROW
    [test] 2014-01-31 18:40:47.163 >>> rowNEW = db.people.find( { "name" : "joe", "age" : 20} );
    { "_id" : ObjectId("52ec316d1d21069b6061b554"), "name" : "joe", "age" : 20 }
    [test] 2014-01-31 18:40:55.73 >>> rowNEW.forEach(function() { print ('FOUND ROW'); } );
    [test] 2014-01-31 18:40:57.533 >>>

The first time 'FOUND ROW' is printed out.
The second time 'FOUND ROW' is not printed out.
This looks very unexpected and weird to me.
Why does it behave that way?

Upvotes: 3

Views: 103

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

Without the var the left side newRow is being eval'd in the shell. It's a REPL, that's why you see the JSON on the next line. This also moves the cursor forward one step, so when you are trying to access the newRow the next time, the cursor is at the end of the results.

use var to avoid the eval.

Upvotes: 4

Related Questions