- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在使用 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(...)
或 bson.EC.Int64(.. .)
。我尝试使用 bson.EC.InterfaceErr(...)
但出现错误
Cannot create element for type *models.NoteUpdate, try using 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 文档构建器实现相同的效果?
更新。我的问题的完整背景:我为 部分 更新“Note”文档(存储在 MongoDB 中)编写了 REST 端点。我现在拥有的代码:
var noteUpdate models.NoteUpdate
ctx.BindJSON(¬eUpdate)
//omit validation and errors handling
updateParams := services.SetWrapper{Set: noteUpdate}
res := collection.FindOneAndUpdate(
context.Background(),
bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)),
updateParams,
findopt.OptReturnDocument(option.After),
)
我想要的代码
var noteUpdate models.NoteUpdate
ctx.BindJSON(¬eUpdate)
//omit validation and errors handling
res := collection.FindOneAndUpdate(
context.Background(),
bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)),
bson.NewDocument(
//bsoncodec.ConstructElement doesn't exists
bsoncodec.ConstructElement("$set", ¬eUpdate)),
),
findopt.OptReturnDocument(option.After),
)
我不想要的代码
var noteUpdate models.NoteUpdate
ctx.BindJSON(¬eUpdate)
//omit validation and errors handling
bsonNote := bson.NewDocument()
if noteUpdate.Title != "" {
bsonNote.Append(bson.EC.String("title", noteUpdate.Title))
}
if noteUpdate.Content != "" {
bsonNote.Append(bson.EC.String("content", noteUpdate.Content))
}
//..setting the rest of the fields...
res := collection.FindOneAndUpdate(
context.Background(),
bson.NewDocument(bson.EC.String("_id", noteUpdate.ID)),
bson.NewDocument(bson.EC.SubDocument("$set", bsonNote)),
findopt.OptReturnDocument(option.After),
)
所以,确切的问题是 - 有没有什么方法可以基于 bson
标签动态构建 *bson.Document(没有像我的 SetWrapper 这样的预定义包装器)?
最佳答案
很遗憾,目前不支持此功能。
您可以创建一个辅助函数,将结构值“转换”为 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()
将来会改进并允许直接传递结构值或指向结构值的指针。
关于mongodb-go-driver/bson struct 到 bson.Document 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53110020/
我有一个数组 items[] items[] 中的每一项都是一个结构体。 item 有键 id、date、value(即 item.id、item.date、item.value) 我想使用 Stru
我想存储 100 名员工。 RollNo,姓名,工资,时间(各种数据,我无法在这里解释,但你可以看下面的代码片段来理解 main() { struct day { int hour
这个问题在这里已经有了答案: storage size of ‘names’ isn’t known (3 个答案) 关闭 5 年前。 我正在尝试蓝牙编程,遇到了这个我不明白的问题。基本上,当我使用
这是一个奇怪的事情: 我有一个结构,它包含指向相同类型结构的指针和指向其他类型结构的指针,以及一些其他值。 struct animal { struct animal * father;
我有一个结构定义如下(名称不同) struct str1 { int field1; struct str2; } 我在一个函数中有一个*str1。我想要一个指向 str2 的指针。 所以
DISK_DETECTION_INFO is defined as有什么原因吗? typedef struct _DISK_DETECTION_INFO { DWORD Size
我正在尝试打包一个字符串和一个字符串的长度。 fmt = '
我在创建结构时遇到问题。 我的结构: public struct Device: Codable { let data: DeviceData let meta: Meta? } pu
struct Item { var name:String? var type:String? var value:Int? var tag:Int? } ... ..
// NewReaderSize returns a new Reader whose buffer has at least the specified 43 // size. If the ar
这个问题在这里已经有了答案: Sorting a vector of custom objects (14 个答案) 关闭 3 年前。 在下面的 C++ 片段中, 如何基于 TwoInts 结构中的
#include struct Header { unsigned long long int alignment; }; int main(void) { struct Heade
我有一个目前看起来像这样的结构(缩写为仅显示基本部分): typedef struct { uint32_t baudrate; ... some other internally u
对此没有太多解释,这就是我所拥有的: public struct PACKET_HEADER { public string computerIp; publi
我有以下代码: struct MyStruct{ data: &'a str, } fn get(S: &'a MyStruct) -> &'a str{ S.data } fn se
struct S1 { char c; int i; }; struct S3 { char c1; struct S1 s; double c2; }; 我正
我有一个名为 Parameter 的协议(protocol): protocol Parameter { var name: String { get } var unit: Unit
有 2 个 struct 定义 A 和 A。我知道 struct A 可以包含指向 struct A 的 POINTER 但我不明白为什么 struct A 不能包含struct A(不是指针) 最佳
我有以下代码: struct MyStruct{ data: &'a str, } fn get(S: &'a MyStruct) -> &'a str{ S.data } fn se
为了说明这一点,这里有一个小的不可变结构和一个更新它的函数: (struct timeseries (variable observations) #:transparent) (define (ad
我是一名优秀的程序员,十分优秀!