跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • golang mongo-driver 如何更新某个字段
未分類
17 1 月 2021

golang mongo-driver 如何更新某个字段

golang mongo-driver 如何更新某个字段

資深大佬 : aoscici 3

 type Comment struct {  ID      primitive.ObjectID `bson:"_id,omitempty"  json:"id"`  Title   string             `bson:"title"          json:"title"       binding:"required"`  Author  string             `bson:"author"         json:"author"      binding:"required"`  Content string             `bson:"content"        json:"content"     binding:"required"`  Like    int64              `bson:"like"           json:"like"`  Updated time.Time          `bson:"updated"        json:"updated"` }  Collection.FindOneAndUpdate(ctx, filter, update, &opt).Decode(&comment)  

比如这里我只传来 {“content”: “。。。”} 或者 {“author”: “11”} 这一个数据,怎么灵活得接收这个数据和只更新这一个字段?翻了很多文章貌似都是把更新项写死的。

大佬有話說 (9)

  • 資深大佬 : teawithlife

    我不确定是否有这样的功能,但是从道理上来说,一个 API 的设计,需要更新哪些字段应该是明确的,不应该随意变化。所以我怀疑你这是一个 XY 问题,可否先讲讲你这个需求产生的原因?

  • 資深大佬 : lithiumii

    直接{’$set’:{‘content’: ‘…’}}就行了吧,没涉及的字段不会变

  • 主 資深大佬 : aoscici

    @teawithlife 比如说我就单独更新一下个人信息的年龄,或者单独更新性别,不知道该怎么操作

  • 主 資深大佬 : aoscici

    @lithiumii 主要是我想能不能单独传一个字段进来,就更新这个字段,而不是所有 required 的字段都要传

  • 資深大佬 : bankroft

    接收 bson.M,set bsonM 不行吗

  • 資深大佬 : useben

    外部传入 map[string]interface{}参数, 内部创建 bson.M,遍历 map[string]interface{}赋值 bson.M, 最后 set bsonM

  • 資深大佬 : yeqown

    @useben 这种方式可行, 补充一点:不推荐直接使用 map[string]interface{} ,可以考虑从模型 struct 转过来,那样就不用关心数据库里字段名是什么了

  • 資深大佬 : useben

    @yeqown 也可以

  • 主 資深大佬 : aoscici

    @useben 谢谢,看着可行哈哈

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具