Primitive.ObjectID转换为字符串 [英] Primitive.ObjectID to string
问题描述
我试图在Go中将原始类型Object.ID转换为字符串.我正在使用go.mongodb.org/mongo-driver
I am trying to convert type primitive.ObjectID to string in Go. I am using mongo-driver from go.mongodb.org/mongo-driver
我尝试使用类似类型的断言
I tried using type assertion like
mongoId := mongoDoc["_id"];
stringObjectID := mongoId.(string)
哪个VSCode接受.代码被编译,并在到达此特定代码行时抛出此错误
Which VSCode accepts. Code gets compiled and when it reaches this specific line of code, it throws this error
panic: interface conversion: interface {} is primitive.ObjectID, not string
推荐答案
错误消息告诉 mongoDoc ["_ id"]
类型为 interface {}
,其中包含一个类型 primitive.ObjectID
一个>.这不是 string
,而是一种不同的类型.您只能从接口值中输入assert primitive.ObjectID
.
The error message tells mongoDoc["_id"]
is of type interface{}
which holds a value of type primitive.ObjectID
. This is not a string
, it's a distinct type. You can only type assert primitive.ObjectID
from the interface value.
如果您想要此MongoDB ObjectId的 string
表示形式,则可以使用其
If you want a string
representation of this MongoDB ObjectId, you may use its ObjectID.Hex()
method to get the hex representation of the ObjectId's bytes:
mongoId := mongoDoc["_id"]
stringObjectID := mongoId.(primitive.ObjectID).Hex()
这篇关于Primitive.ObjectID转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!