【问题标题】:How to unmarshal a BSON string value into a custom type using go-mongo-driver?如何使用 go-mongo-driver 将 BSON 字符串值解组为自定义类型?
【发布时间】:2021-07-18 14:45:00
【问题描述】:

我正在使用 MarshalBSONValue 将内部结构字段编组为自定义字符串表示形式。

我不知道如何实现逆操作 UnmarshalBSONValue,以便将自定义字符串表示解析为内部结构。

import (
    "fmt"
    "testing"

    "github.com/stretchr/testify/assert"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/bson/bsontype"
)

type inner struct {
    value string
}

func (i inner) MarshalBSONValue() (bsontype.Type, []byte, error) {
    return bsontype.String, []byte(i.value), nil
}

// How to implement this?
//
// func (i *inner) UnmarshalBSONValue(t bsontype.Type, data []byte) error {
//     ...
// }

type Outer struct {
    Inner inner `bson:"inner"`
}

func TestMarshalBSON(t *testing.T) {
    var outer1 = Outer{Inner: inner{value: "value"}}
    doc, err := bson.Marshal(outer1)
    assert.NoError(t, err)
    fmt.Printf("%#v\n", string(doc)) // "\x11\x00\x00\x00\x02inner\x00value\x00"

    var outer2 Outer
    err = bson.Unmarshal(doc, &outer2) // error
    assert.NoError(t, err)

    assert.Equal(t, outer1, outer2)
}

如果有人能为上面的示例测试提供 UnmarshalBSONValue 的工作实现,我将不胜感激。

【问题讨论】:

    标签: mongodb go bson


    【解决方案1】:

    您可以使用bsoncore.ReadString 来解析给定的值。

    func (i inner) MarshalBSONValue() (bsontype.Type, []byte, error) {
        return bson.MarshalValue(i.value)
    }
    
    func (i *inner) UnmarshalBSONValue(t bsontype.Type, value []byte) error {
        if t != bsontype.String {
            return fmt.Errorf("invalid bson value type '%s'", t.String())
        }
        s, _, ok := bsoncore.ReadString(value)
        if !ok {
            return fmt.Errorf("invalid bson string value")
        }
    
        i.value = s
        return nil
    }
    

    【讨论】:

    • 谢谢!但是 UnmarshalBSONValue 似乎没有使用上面的测试方法调用。
    • @titaniumdecoy 它对我有用:play.golang.org/p/zidkH4NIZpn
    • 啊,我看到我的 MarshalBSONValue 实现不正确。非常感谢!
    猜你喜欢
    • 2020-09-26
    • 2019-10-17
    • 1970-01-01
    • 2021-11-26
    • 2014-02-04
    • 2018-02-04
    • 1970-01-01
    • 2019-01-05
    • 2022-01-12
    相关资源
    最近更新 更多