
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"} 这一个数据,怎么灵活得接收这个数据和只更新这一个字段?翻了很多文章貌似都是把更新项写死的。
1 teawithlife 2021-01-24 18:56:16 +08:00 我不确定是否有这样的功能,但是从道理上来说,一个 API 的设计,需要更新哪些字段应该是明确的,不应该随意变化。所以我怀疑你这是一个 XY 问题,可否先讲讲你这个需求产生的原因? |
2 lithiumii 2021-01-24 19:06:28 +08:00 via Android 直接{'$set':{'content': '...'}}就行了吧,没涉及的字段不会变 |
3 aoscici OP @teawithlife 比如说我就单独更新一下个人信息的年龄,或者单独更新性别,不知道该怎么操作 |
5 bankroft 2021-01-24 19:42:50 +08:00 接收 bson.M,set bsonM 不行吗 |
6 useben 2021-01-24 23:59:54+08:00 外部传入 map[string]interface{}参数, 内部创建 bson.M,遍历 map[string]interface{}赋值 bson.M, 最后 set bsonM |