Primitive.ObjectID 到 Golang 中的字符串 [英] Primitive.ObjectID to string in Golang
问题描述
我正在尝试在 Go 中将 primitive.ObjectID
类型转换为 string
类型.我正在使用 go.mongodb.org/mongo-driver
中的 mongo-driver
.
I am trying to convert type primitive.ObjectID
to string
type in Go. I am using mongo-driver
from go.mongodb.org/mongo-driver
.
我尝试使用类型断言
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
表示,你可以使用它的 ObjectID.Hex()
方法来获取 ObjectId 字节的十六进制表示:
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 到 Golang 中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!