4

I'm receiving:

[Error: Bad BSON Document: illegal CString]

When using the Node MongoDB driver while iterating over one of my collections with Cursor.each. It seems to make some of my documents disappear, and not found in the collection, even though they were individually accessible when I look for them using Collection.findOne().

Does this mean that my data is corrupted in some way?

Clarence Leung
  • 2,446
  • 21
  • 24
  • 2
    The driver is having trouble deserializing a string. Glancing at the [code](https://github.com/mongodb/js-bson/blob/master/ext/bson.cc), it might be a missing null byte at the end of the string. Can you access the data? What happens if you query the bad document in the shell? You could also try using [validate](http://docs.mongodb.org/manual/reference/method/db.collection.validate/) to check for problems with the data. – wdberkeley Jan 12 '15 at 16:01
  • I'm having difficulty determining which document is the bad document that's causing this error. All the Node MongoDB driver is giving me is an error, with no ObjectID I can use to query for it. – Clarence Leung Jan 12 '15 at 16:07

1 Answers1

2

Thanks to @wdberkeley for all the help in the above comment, which helped me to track down my problem.

It turns out that I did have a single corrupted document in my collection, which was inserted during an unclean shutdown of Mongo. I was unaware how that document would affect the rest of my queries though.

When you perform a collection.find(), and then start iterating with the cursor over the collection, the cursor will stop and be unable to go any further if it encounters an error, such as with [Error: Bad BSON Document: illegal CString].

This happens with both cursor.forEach or cursor.nextObject. Thus, I was unable to access any of the documents that came after the error in the collection, even though I was able to access those documents individually with collection.findOne.

The only solution in this scenario for me was to run db.repairDatabase, which removed the corrupted documents, and solved the problem for me.

Clarence Leung
  • 2,446
  • 21
  • 24