如何在Golang中将UUID存储到MongoDB?

5

在 Golang 中,使用 github.com/google/uuid 存储 UUID 字段到 MongoDB 时,会将其转换为 subtype 为 0 的 base64 二进制格式。这使得按照 UUID 查询文档字段变得不可能。

插入的用户数据如下:

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

使用生成的UUID d1b1d8a0-d592-4d5f-8aa9-64a5e7861689 进行查询时,结果为空。

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
}
1个回答

5
由于 github.com/google/uuid UUID 类型的本质是 [16]byte 的别名,Mongo 将使用二进制子类型 0x00 的 BSON 二进制方式存储它。试图将 UUID 转换为 BSON 的 base64 二进制格式是不切实际的。因此,您可以选择使用我编写的编码器和解码器特性,该特性可以直接插入到 mongo 客户端结构中,链接如下: https://gist.github.com/SupaHam/3afe982dc75039356723600ccc91ff77

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接