SimonTheLeg
SimonTheLeg

Reputation: 57

How to convert mongo.InsertOneResult's InsertedID to []byte

Hi all I am struggling to convert the InsertedID of an InsertOne() Operation to a byte slice*. I am using this mongoDB client library https://github.com/mongodb/mongo-go-driver


So far I have tried to use TypeAssertion directly like this:

res.InsertedID.([]byte)

which compiles, but results in the following error during the assertion:

panic: interface conversion: interface {} is primitive.ObjectID, not []uint8

I have also tried to use multiple TypeAssertions or the []byte() function directly, but could not get it to compile


*byte slice is in this case desired because I am using gRPC, which limits the possible types I can use for return values.

Upvotes: 1

Views: 2661

Answers (2)

Burak Serdar
Burak Serdar

Reputation: 51567

The InsertedID is a primitive.ObjectID, which is [12]byte. So you can do this to get a byte slice:

oid:=res.InsertedID.(primitive.ObjectID)
slice:=oid[:]

Upvotes: 4

beiping96
beiping96

Reputation: 644

https://godoc.org/go.mongodb.org/mongo-driver/bson/primitive#ObjectID

guess that's you want

first, you can assert InsertedID to primitive.ObjectID, then convert to string or something else

res.InsertedID.(primitive.ObjectID).String()
res.InsertedID.(primitive.ObjectID).Hex()

Upvotes: 3

Related Questions