mgo NewObjectId corrupt on insert

夙愿已清 提交于 2019-12-12 06:22:34

问题


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"`
    ...
}

回答1:


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.



来源:https://stackoverflow.com/questions/31244438/mgo-newobjectid-corrupt-on-insert

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!