Search code examples
mongodbgomgo

mgo NewObjectId corrupt on insert


If I generate a new object id for a document in mgo:

obId := bson.NewObjectId()

and then insert it, it ends up in mongo (looking via the cli) as

"_id" : "U�`�\u0006@�\rU\u0000\u0000\u0001"

When it should be

"_id" : ObjectId("559a47643d9827f0d9405420")

Same goes if I try and update an existing document where I generate the id by

obId := bson.ObjectIdHex(stringId)

It still gets serialized to the corrupted format.

My struct which I'm trying to insert looks like this:

type MyStruct struct {
    Id            bson.ObjectId `bson:"_id,omitempty" json:"id"`
    ...
}

Solution

  • The representation "U�`�\u0006@�\rU\u0000\u0000\u0001" is clearly indicating that an ObjectId got sent to the database as a string rather than as a properly typed object id. Every such case before was a code path in the application side delivering the string explicitly as such by mistake. I recommend investigating every code path that inserts objects in that collection, and if you can find no case that is sending it as an actual string, then try to create a reproducer and report it upstream to the mgo driver.

    Update: Per your comment below, the issue is being caused because some part of the application is using an ObjectId type from a package that is not the one actually used during communication with the database. This has the effect described above: the ObjectId type coming from the wrong package is just a normal string, as far as the correct bson package is concerned.