skip to Main Content

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


  1. Chosen as BEST ANSWER

    it worked, very simple

    type Document struct {
    ID         primitive.Binary `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"`
    }
    
        id := uuid.New()
    
        binId := primitive.Binary{
            Subtype: 0x04,
            Data:    id[:],
        }
    

  2. 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

    import (
        "github.com/google/uuid"
        "go.mongodb.org/mongo-driver/bson"
        "go.mongodb.org/mongo-driver/mongo"
    )
    
    // Defined my document struct
    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"`
    }
    
    func main() {
    
        // then, Create a new UUID of type 0x04
        id := uuid.New()
        
            // Serialize the UUID as a binary subtype 0x04
        idBytes := id.Bytes()
        idBytes[6] = (idBytes[6] & 0x0f) | 0x40 // Set the version byte to 4
        idBytes[8] = (idBytes[8] & 0x3f) | 0x80 // Set the variant byte to the RFC 4122 variant
        idBinary := bson.Binary{
            Subtype: 0x04,
            Data:    idBytes,
        }
        fmt.Println("🚀  idBinary : ", idBinary)
    
        // now, Create a new document instance
        doc := &Document{
            ID:         uuid.Nil, // this, ID will be automatically generated by MongoDB
            FcrID:      "my-fcr-id",
            ContextKey: "my-context-key",
            PrivateKey: "my-private-key",
            PublicKey:  "my-public-key",
        }
        
        fmt.Println("🚀  doc : ", doc)
        // Serialize the document to BSON
        bsonDoc, err := bson.Marshal(doc)
        if err != nil {
            fmt.Println("🚀 ~ marshal : ~ err : ", err)
            
        }
    
        // Set the ID field to the binary UUID value
        bsonDoc[4] = 0x04 // Set the BSON type for the ID field to binary
        bsonDoc = append(bsonDoc[:5], idBinary.Bytes()...)
        bsonDoc = append(bsonDoc, 0x00) // Add a null terminator to the BSON document
    
        // Insert the document into the MongoDB collection using insertOne() command
        collection := mclient.Database("MyDB").Collection("MyCollection")
        _, err = collection.InsertOne(ctx, bsonDoc)
        if err != nil {
            fmt.Println("🚀 ~ insertOne(): ~ err : ", err)
            
        }
    }
    

    you first generate a new UUID using the uuid.New() function. then, you serialize the UUID as a binary subtype 0x04 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 the collection.InsertOne() function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search