mongodb 字符串转bson_mongodb-go-driver / bson结构转换为bson.Document编码

本文讨论如何在Go中使用mongodb-go-driver/bson库,将结构体自动转换为bson.Document,特别是处理部分更新操作时,如何避免手动编码每个非空字段。
摘要由CSDN通过智能技术生成

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(...)或手动编码每个非空字段bson.EC.Int64(...)。我尝试使用bson.EC.InterfaceErr(...)但出现错误

无法为* models.NoteUpdate类型创建元素࿰

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值