MongoDB error: An error occurred while deserializing the _id field of class … : Cannot deserialize string from BsonType ObjectId.
The last few weeks I’m having fun learning MongoDB. Having some experience with RavenDB, I hoped to re-use most of knowledge when building a MongoDB backend. However I have to conclude that no two No-SQL solutions are alike, so there is still a high learning curve.
I created a sample application, but when I tried to load some objects from the database, I got the following error:
An error occurred while deserializing the _id field of class Product: Cannot deserialize string from BsonType ObjectId.
Let’s have a look at the object I was using; I have a Product class with 2 properties and an ‘_id’ field. The ‘_id’ field is automatically generated by MongoDB for every object you create.
The problem is that behind the scenes MongoDB is storing all objects as BSON documents in the database. The ‘_id’ field isn’t an ordinary string but an ObjectId, a 12-byte BSON type, constructed using:
- a 4-byte value representing the seconds since the Unix epoch,
- a 3-byte machine identifier,
- a 2-byte process id, and
- a 3-byte counter, starting with a random value.
To fix our error, we have to update our Product class to use the ObjectId type: