christkv/node-mongodb-native — Issue #442: infinite streamRecords QueryFailure fix
Author: d1april
Created: 2011-12-15 10:57:51+00:00
State: open

I had the problem with cursor.streamRecords that it streamed an infinite amount of documents or until the given limit was reached.
This happened only with an connection to mongos, while a connection to mongod was fine.

After the documents I supposed to get were received I got an infinite amount of those error documents:
{ '$err': 'assertion s/cursors.cpp:179', code: 0 }

To debug it I added this this to the cursor.js Cursor.prototype.streamRecords:

```
function execute(command) {
self.db._executeQueryCommand(command, {read:true, raw:self.raw}, function(err,result) {
console.log('cursor result: '+err+' '+require('util').inspect(result,false,2));
```

This was the output:
```
cursor result: null { documents: [ all fine documents ],
index: 521134,
messageLength: 521134,
requestId: 852709,
responseTo: 5,
responseFlag: 8,
cursorId: 0,
startingFrom: 0,
numberReturned: 75 }
cursor result: null { documents: [ { '$err': 'assertion s/cursors.cpp:179', code: 0 } ],
index: 89,
messageLength: 89,
requestId: 852743,
responseTo: 6,
responseFlag: 2,
cursorId: 0,
startingFrom: 0,
numberReturned: 1 }
```

I looked up what the responseFlag means: http://www.mongodb.org/display/DOCS/Mongo+Wire+Protocol#MongoWireProtocol-OPREPLY
1	QueryFailure	Set when query failed. Results consist of one document containing an "$err" field describing the failure.

This is how I fixed it:
Replace:
```
if (result.documents && result.documents.length) {
```
With:
```
var resflagsMap={
CursorNotFound:1<<0,
QueryFailure:1<<1,
ShardConfigStale:1<<2,
AwaitCapable:1<<3
};
if (result.documents && result.documents.length && !(result.responseFlag&resflagsMap.QueryFailure)) {
```

I hope it helps.