Sup*_*Ham 6 uuid encode go mongodb
当使用 Golang 在 MongoDB 中存储github.com/google/uuidUUID 字段时,它会转换为子类型 0 的 Base64 二进制文件。这使得无法通过 UUID 自然地查询文档字段。
插入的用户如下所示:
{"_id":{"$binary":"0bHYoNWSTV+KqWSl54YWiQ==","$type":"0"},"name":"Isabella"}
Run Code Online (Sandbox Code Playgroud)
通过生成的 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
}
Run Code Online (Sandbox Code Playgroud)
由于github.com/google/uuidUUID 类型的性质是 的别名[16]byte,Mongo 将其存储为子类型 0x00 的 BSON 二进制文件。尝试将 UUID 转换为 BSON 的 Base64 二进制格式是不切实际的。因此,您可以选择使用我编写的编码器和解码器功能,该功能可以直接插入此处的 mongo 客户端结构中:https ://gist.github.com/SupaHam/3afe982dc75039356723600ccc91ff77