How to store a UUID in MongoDB with Golang?
Asked Answered
C

1

7

When storing a github.com/google/uuid UUID field in MongoDB using Golang it translates to a base64 binary with subtype 0. This makes it impossible to naturally query the document field by UUID.

The inserted user looks like:

{"_id":{"$binary":"0bHYoNWSTV+KqWSl54YWiQ==","$type":"0"},"name":"Isabella"}

When querying by the generated UUID d1b1d8a0-d592-4d5f-8aa9-64a5e7861689, the results are empty.

type User struct {
    UserId uuid.UUID `json:"userId" bson:"_id"`
    Name   string    `json:"name" bson:"name"`
}

func (repo userRepo) User(uuidIn uuid.UUID) (model.User, error) {
    collection := repo.database.Collection(mongoCollectionUser)
    var user model.User
    err := collection.FindOne(context.Background(),
        bson.M{"_id": uuidIn},
    ).Decode(&user)
    // err: mongo: no documents in result
}
Counterblow answered 6/11, 2020 at 23:55 Comment(0)
C
7

Due to the nature of github.com/google/uuid UUID type being an alias of [16]byte, Mongo will resort to storing it as a BSON Binary of subtype 0x00. It is impractical to attempt to convert the UUID to a base64 binary format for BSON. So you may choose to use this encoder & decoder feature I wrote that can be plugged directly into the mongo client struct here: https://gist.github.com/SupaHam/3afe982dc75039356723600ccc91ff77

Counterblow answered 6/11, 2020 at 23:55 Comment(1)
This uses the deprecated factory and a magic number (0x04) for the subtype. I've adjusted the gist accordingly here: gist.github.com/UlrichEckhardt/2c5eff33681fde475dd54f9c4b665831.Kuster

© 2022 - 2024 — McMap. All rights reserved.