Primitive.ObjectID to string in Golang

Viewed 22834

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
4 Answers

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

Things have changed in 2021. Here is a more easy way. It takes the user from models asking what kind of type it is from interface then all good

var user models.User

query := bson.M{"$or": []bson.M{{"username": data["username"]}, {"email": data["username"]}}}

todoCollection := config.MI.DB.Collection(os.Getenv("DATABASE_COLLECTION_USER"))
todoCollection.FindOne(c.Context(), query).Decode(&user)

stringObjectID := user.ObjectID.Hex()

Above code works with this interface:

type User struct {
    ObjectID primitive.ObjectID `bson:"_id" json:"_id"`

    // Id        string    `json:"id" bson:"id"`
    Username      string    `json:"username" gorm:"unique" bson:"username,omitempty"`
    Email         string    `json:"email" gorm:"unique" bson:"email,omitempty"`
    Password      []byte    `json:"password" bson:"password"`
    CreatedAt     time.Time `json:"createdat" bson:"createat"`
    DeactivatedAt time.Time `json:"updatedat" bson:"updatedat"`
}

So consequently: this 3 line codes would do it nicely:

objectidhere := primitive.NewObjectID()
stringObjectID := objectidhere.Hex()

filename_last := filename_rep + "_" + stringObjectID + "." + fileExt

nowadays you can just do mongoId.Hex()

var stringObjectId string = mongoId.(primitive.ObjectID).String()
Related