mgo NewObjectId在插入时损坏

huangapple go评论84阅读模式
英文:

mgo NewObjectId corrupt on insert

问题

如果我为mgo中的文档生成一个新的对象ID:

obId := bson.NewObjectId()

然后将其插入,它会以以下方式出现在Mongo中(通过cli查看):

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

而实际上应该是:

"_id" : ObjectId("559a47643d9827f0d9405420")

如果我尝试更新一个现有文档,其中我通过以下方式生成ID:

obId := bson.ObjectIdHex(stringId)

它仍然会被序列化为损坏的格式。

我尝试插入的结构体如下所示:

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

英文:

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

得分: 3

表示"U�`�\u0006@�\rU\u0000\u0000\u0001"明显表明一个ObjectId以字符串形式而不是正确的类型化对象id发送到了数据库。之前的每个这样的情况都是应用程序端的代码路径通过错误地显式地传递字符串来发送的。我建议调查每个将对象插入该集合的代码路径,如果找不到将其作为实际字符串发送的情况,那么尝试创建一个可重现的示例并将其上报给mgo驱动的上游。

**更新:**根据您下面的评论,问题是由于应用程序的某个部分使用了一个与实际与数据库通信时使用的包不同的ObjectId类型。这会产生上述描述的效果:来自错误包的ObjectId类型只是一个普通字符串,对于正确的bson包来说。

英文:

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.

huangapple
  • 本文由 发表于 2015年7月6日 19:16:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/31244438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定