mongodb-go-driver/bson struct to bson.Document encoding

前端 未结 1 1477
孤街浪徒
孤街浪徒 2021-02-09 01:51

I\'m working with https://github.com/mongodb/mongo-go-driver and currently trying to implement a partial update of such struct

type NoteUpdate struct {
    ID            


        
1条回答
  •  无人共我
    2021-02-09 02:27

    Unfortunately this is currently not supported.

    You may create a helper function which "converts" a struct value to a bson.Document like this:

    func toDoc(v interface{}) (doc *bson.Document, err error) {
        data, err := bson.Marshal(v)
        if err != nil {
            return
        }
    
        err = bson.Unmarshal(data, &doc)
        return
    }
    

    Then it can be used like this:

    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)),
    )
    

    Hopefully ElementConstructor.Interface() will improve in the future and allow passing struct values or pointers to struct values directly.

    0 讨论(0)
提交回复
热议问题