0

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"`
    ...
}
byrnedo
  • 1,415
  • 10
  • 12
  • How do you print it where it appears as `"_id" : "U�`�\u0006@�\rU\u0000\u0000\u0001"`? – icza Jul 06 '15 at 11:49
  • I'm using the `mongo` cli command and just copying the output of `db.mycol.find()`. Thing is, ids that were autogenerated appear as `ObjectId("blah...")` – byrnedo Jul 06 '15 at 11:57

1 Answers1

3

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.

Gustavo Niemeyer
  • 22,007
  • 5
  • 57
  • 46
  • The issue is hopefully solved. I am using a library which imports mgo via `gopkg.in/mgo.v2`. I was importing mgo myself as well as `gopkg.in/v2/mgo`. After copying the external code into the project and making them all import from `labix.org/v2/mgo` it now works. So the path confusion possibly caused it. – byrnedo Jul 06 '15 at 14:38
  • 1
    labix.org/v2/mgo is extremely old. Please use gopkg.in/mgo.v2 instead. – Gustavo Niemeyer Jul 06 '15 at 15:04
  • Thanks @Gustavo, will update the imports to that path. – byrnedo Jul 07 '15 at 18:34