Primitive.ObjectID to string in Golang

Rabi picture Rabi · Mar 26, 2020 · Viewed 7.9k times · Source

I am trying to convert type primitive.ObjectID to string type 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)

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

Answer

icza picture icza · Mar 26, 2020

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.

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()