23

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
John Smith
  • 7,243
  • 6
  • 49
  • 61
Rabi
  • 359
  • 1
  • 2
  • 7
  • It's impossible to tell you how to convert `primitive.ObjectID` to a string if you don't tell us how `primitive.ObjectID` is defined. – Jonathan Hall Mar 26 '20 at 10:21
  • hi Flimzy, It was defined like this var parentOrder bson.M; and appened into slice array, and the slice array was defined like this var mapArray []bson.M Function loops through this slice array to scan _id like I explained above. mongoDoc is one single mongo document of type bson.M – Rabi Mar 26 '20 at 10:31
  • Please update the question with that information. – Jonathan Hall Mar 26 '20 at 10:32

4 Answers4

36

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()
icza
  • 389,944
  • 63
  • 907
  • 827
4

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
Bitfinicon
  • 1,045
  • 1
  • 8
  • 22
4

nowadays you can just do mongoId.Hex()

bashizip
  • 562
  • 5
  • 14
1
var stringObjectId string = mongoId.(primitive.ObjectID).String()
patrik kings
  • 442
  • 6
  • 15