UUID 作为 _id 错误 - 不能将数组用于 _id

UUID as _id error - can't use an array for _id

我正在尝试为 MongoDB 中的 _id 字段使用 UUID。

我有一个包装器结构来保存我的记录,如下所示:

type mongoWrapper struct {
    ID      uuid.UUID       `bson:"_id" json:"_id"`
    Payment storage.Payment `bson:"payment" json:"payment"`
}

这是我围绕 MongoDB 驱动程序包中的 InsertOne 函数编写的代码:

func (s *Storage) Create(newPayment storage.Payment) (uuid.UUID, error) {
    mongoInsert := wrap(newPayment)
    c := s.client.Database(thisDatabase).Collection(thisCollection)

    insertResult, errInsert := c.InsertOne(context.TODO(), mongoInsert)
    if errInsert != nil {
        return uuid.Nil, errInsert
    }

    fmt.Println("Inserted a single document: ", insertResult.InsertedID)

    return mongoInsert.ID, nil
}

这是我的 wrap() 函数,它包装了支付记录数据,并采用可选的 UUID 参数或相应地生成它自己的参数:

func wrap(p storage.Payment, i ...uuid.UUID) *mongoWrapper {
    mw := &mongoWrapper{ID: uuid.Nil, Payment: p}

    if len(i) > 0 {
        mw.ID = i[0]
        return mw
    }

    newID, errID := uuid.NewV4()
    if errID != nil {
        log.Fatal(errID)
    }

    mw.ID = newID

    return mw
}

当我的一个测试调用 Create() 时 returns 出现以下错误:

storage_test.go:38: err: multiple write errors: [{write errors: [{can't use an array for _id}]}, {<nil>}]

我正在为我的 UUID 和 MongoDB 驱动程序使用以下软件包:

import(
    uuid "github.com/satori/go.uuid"

    "go.mongodb.org/mongo-driver/mongo"
)

我不清楚具体问题出在哪里。

我是否需要围绕 UUID 进行一些额外的管道处理才能正确处理它?

编辑: 我做了更多更改,但 UUID 仍然作为数组出现:

type mongoWrapper struct {
    UUID    mongoUUID       `bson:"uuid" json:"uuid"`
    Payment storage.Payment `bson:"payment" json:"payment"`
}

type mongoUUID struct {
    uuid.UUID
}

func (mu *mongoUUID) MarshalBSON() ([]byte, error) {
    return []byte(mu.UUID.String()), nil
}

func (mu *mongoUUID) UnmarshalBSON(b []byte) error {
    mu.UUID = uuid.FromStringOrNil(string(b))
    return nil
}

uuid.UUID 是引擎盖下的 [16]byte

但是,这种类型还实现了 encoding.TextMarshaler 接口,我希望 mongo 能够实现(与 json 包一样)。

我认为解决方案是创建自己的类型,嵌入 uuid.UUID 类型,并提供 bson.Marshaler interface.

的自定义实现

我来到下面的实现作为解决方案:

type mongoUUID struct {
    uuid.UUID
}

func (mu mongoUUID) MarshalBSONValue() (bsontype.Type, []byte, error) {
    return bsontype.Binary, bsoncore.AppendBinary(nil, 4, mu.UUID[:]), nil
}

func (mu *mongoUUID) UnmarshalBSONValue(t bsontype.Type, raw []byte) error {
    if t != bsontype.Binary {
        return fmt.Errorf("invalid format on unmarshal bson value")
    }

    _, data, _, ok := bsoncore.ReadBinary(raw)
    if !ok {
        return fmt.Errorf("not enough bytes to unmarshal bson value")
    }

    copy(mu.UUID[:], data)

    return nil
}