I am trying to store in mongodb a uuid type 4 but when I call the InsertOne function this is storing my uuid as type 0 (generic) and not type 4.
I don’t know exactly what I am doing wrong.
My code:
type Document struct {
ID uuid.UUID `bson:"_id" json:"id"`
FcrID string `bson:"fcrId" json:"fcrId"`
ContextKey string `bson:"contextKey" json:"contextKey"`
PrivateKey string `bson:"privateKey" json:"privateKey"`
PublicKey string `bson:"publicKey" json:"publicKey"`
}
for _, message := range messages {
body := message.Body
fmt.Println("new messaged received, writing keys to database")
id := uuid.New()
var jsonDocument common.DocumentKey
err = json.Unmarshal(body, &jsonDocument)
if err != nil {
fmt.Println(err)
return
}
d, bsonErr := bson.Marshal(common.Document{
ID: id,
FcrID: jsonDocument.FcrID,
ContextKey: jsonDocument.ContextKey,
PrivateKey: jsonDocument.PrivateKey,
PublicKey: jsonDocument.PublicKey,
})
if bsonErr != nil {
fmt.Println(bsonErr)
return
}
err = databaseOperations.InsertData(ctx, mclient, "management", "keys", d)
if err != nil {
fmt.Println(err)
return
}
err = receiver.CompleteMessage(context.TODO(), message, nil)
if err != nil {
log.Println(err)
}
}
but the id is being stored as BinData 0 but I would like to have BinData 4.
I know uuid will return a [16]byte but I don’t understand why mongo is understanding it as a generic data to be stored and not as a proper uuid type 0x04.
how can I make mongodb store my uuid as type 4 and not 0?
Thank you
2
Answers
it worked, very simple
if you want to store a UUID as type 0x04 in MongoDB using Golang, you need to ensure that the UUID is properly serialized as a binary subtype
0x04
before being inserted into the database.here, i can give you an example code snippet that shows how to generate a UUID type
0x04
and store it in MongoDB:Sample Code
you first generate a new UUID using the
uuid.New()
function. then, you serialize the UUID as a binary subtype0x04
by setting the version byte to 4 and the variant byte to the RFC 4122 variant.you create a new document instance and serialize it to BSON using the
bson.Marshal()
function. Finally, you set the ID field to the binary UUID value and insert the document into the MongoDB collection using thecollection.InsertOne()
function.