小编Dan*_*kov的帖子

mongodb-go-driver/bson struct 到 bson.Document 编码

我正在与https://github.com/mongodb/mongo-go-driver 合作,目前正在尝试实现此类结构的部分更新

type NoteUpdate struct {
    ID        string `json:"id,omitempty" bson:"_id,omitempty"`
    Title     string `json:"title" bson:"title,omitempty"`
    Content   string `json:"content" bson:"content,omitempty"`
    ChangedAt int64  `json:"changed_at" bson:"changed_at"`
}
Run Code Online (Sandbox Code Playgroud)

例如,如果我有

noteUpdate := NoteUpdate{ Title: "New Title" }
Run Code Online (Sandbox Code Playgroud)

然后我希望存储文档中唯一的“标题”字段将被更改。

我需要写一些类似的东西

collection.FindOneAndUpdate(context.Background(),
    bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)),
    // I need to encode non-empty fields here
    bson.NewDocument(bson.EC.SubDocument("$set", bson.NewDocument(...)))
)
Run Code Online (Sandbox Code Playgroud)

问题是我不想用bson.EC.String(...)or手动编码每个非空字段bson.EC.Int64(...)。我尝试使用bson.EC.InterfaceErr(...)但出现错误

无法为 *models.NoteUpdate 类型创建元素,请尝试使用 bsoncodec.ConstructElementErr

不幸的是,bsoncodec 中没有这样的功能。我发现的唯一方法是创建包装器

type SetWrapper struct {
    Set interface{} `bson:"$set,omitempty"`
}
Run Code Online (Sandbox Code Playgroud)

并使用它

partialUpdate := &NoteUpdate{
    ID: "some-note-id", 
    Title: "Some new title", …
Run Code Online (Sandbox Code Playgroud)

go mongodb bson mongo-go

10
推荐指数
1
解决办法
1万
查看次数

标签 统计

bson ×1

go ×1

mongo-go ×1

mongodb ×1