我得到的错误WriteValueBytes can only write while positioned on a Element or Value but is positioned on a TopLevel
尝试创建bson.M定制mashler / unmashler时
我有一个名为TransactionId的自定义类型,它表示一个UUID,我想在存储到monbodb之前将此值转换为字符串,并在从mongodb中提取该值时也将其从字符串转换回。
这是我到目前为止的代码
package main
import (
"github.com/google/uuid"
"github.com/pkg/errors"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/bson"
"log"
)
// TransactionID is a UUID used to trace a batch of work which is being processed.
type TransactionID uuid.UUID
// String returns the transaction id as a string
func (id TransactionID) String() (result string, err error) {
val, err := uuid.FromBytes(id[:])
if err != nil {
return result, errors.Wrapf(err, "cannot convert transaction ID %s to UUID", string(id[:]))
}
return val.String(), nil
}
func (id TransactionID) MarshalBSONValue() (bsontype.Type, []byte, error) {
idString, err := id.String()
if err != nil {
return bsontype.String, nil, err
}
return bsontype.String, bsoncore.AppendString(nil, idString), nil
}
func (id *TransactionID) UnmarshalBSONValue(bsonType bsontype.Type, bytes []byte) error {
uid, err := uuid.FromBytes(bytes)
if err != nil {
return err
}
*id = TransactionID(uid)
return nil
}
func NewTransactionID() TransactionID {
return TransactionID(uuid.New())
}
func main() {
id := NewTransactionID()
_, err := bson.Marshal(id)
if err != nil {
log.Fatal(err)
}
}
我正在WriteValueBytes can only write while positioned on a Element or Value but is positioned on a TopLevel
采取非军事步骤。
我得到WriteValueBytes只能在定位在元素或值上时写入,而在解组步骤中定位在TopLevel上。
函数bson.Marshal()需要一个可以转换为文档(即interface{}
)的参数。这就是为什么错误消息与值的位置有关。也就是说,您不能在文档的顶层使用字符串,它必须是文档的元素。如果需要封送单个值,则应改用bson.MarshalValue()。
id := NewTransactionID()
vtype, vdata, err := bson.MarshalValue(id)
bson.Marshal()
下面是一个示例(添加到您的示例中):
type Foo struct {
ID TransactionID
}
func main() {
id := NewTransactionID()
foo, err := bson.Marshal(&Foo{ID:id})
if err != nil {
panic(err)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句