我正在使用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"`}例如,如果我有noteUpdate := NoteUpdate{ Title: "New Title" }然后我希望存儲文檔中唯一的“標題”字段將被更改。我需要寫類似的東西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(...))))問題是我不想用bson.EC.String(...)or手動編碼每個非空字段bson.EC.Int64(...)。我嘗試使用bson.EC.InterfaceErr(...)但出現錯誤無法為 *models.NoteUpdate 類型創建元素,請嘗試使用 bsoncodec.ConstructElementErr不幸的是,bsoncodec 中沒有這樣的功能。我發現的唯一方法是創建包裝器type SetWrapper struct { Set interface{} `bson:"$set,omitempty"`}并像使用它partialUpdate := &NoteUpdate{ ID: "some-note-id", Title: "Some new title", }updateParam := SetWrapper{Set: partialUpdate}collection.FindOneAndUpdate( context.Background(), bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)), updateParam,)它有效,但是否可以使用 bson/bsoncodec 文檔構建器實現相同的效果?更新。我的問題的完整上下文:我編寫了用于部分更新“注釋”文檔(存儲在 MongoDB 中)的 REST 端點。我現在擁有的代碼:var noteUpdate models.NoteUpdatectx.BindJSON(¬eUpdate) //omit validation and errors handlingupdateParams := services.SetWrapper{Set: noteUpdate}res := collection.FindOneAndUpdate(context.Background(),bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)), updateParams, findopt.OptReturnDocument(option.After),)所以,確切的問題是——有沒有什么方法可以基于bson標簽動態構建 *bson.Document(沒有像我的 SetWrapper 這樣的預定義包裝器)?
1 回答

尚方寶劍之說
TA貢獻1788條經驗 獲得超4個贊
不幸的是,目前不支持此功能。
您可以創建一個輔助函數,將結構值“轉換”為bson.D
如下所示:
func toDoc(v interface{}) (doc *bson.D, err error) {
? ? data, err := bson.Marshal(v)
? ? if err != nil {
? ? ? ? return
? ? }
? ? err = bson.Unmarshal(data, &doc)
? ? return
}
然后它可以像這樣使用:
partialUpdate := &NoteUpdate{
? ? Title: "Some new title",
}
doc, err := toDoc(partialUpdate)
// check error
res := c.FindOneAndUpdate(
? ? context.Background(),
? ? bson.NewDocument(bson.EC.String("_id", "some-note-id")),
? ? bson.NewDocument(bson.EC.SubDocument("$set", doc)),
)
希望ElementConstructor.Interface()
將來會改進并允許直接傳遞結構值或指向結構值的指針。
- 1 回答
- 0 關注
- 145 瀏覽
添加回答
舉報
0/150
提交
取消