在 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
}