'How to decode a string in a MongoDB document into a custom business struct in Go?
I have a business object that has a single string, "code", that needs to be persisted in a document to our MongoDB. I need to convert the code into our ClientCode business object when the document is fetched from MongoDB.
So, in more detail:
BUSINESS OBJECTS - simplified
type ClientCode struct {
Code string `bson:"code" json:"code"`
}
type Project struct {
Name string `bson:"name" json:"name"`
Code ClientCode `bson:"clientCode" json:"clientCode"`
}
p := Project{
Name: "Abc",
Code: ClientCode{Code: "abccorp"}
}
I would like to register a converter that would serialize this instance of a Project to database collection: projects,
[
{
"name":"Abc",
"code":"abccorp"
}
]
I would like to register a converter that deserializes the project document in the database into an instance of Project. This process has to deserialize the ClientCode field, too.
I have not been able to find much information about implementing custom encoders/decoders for embedded Go structs in a document in MongoDB. I have implemented custom converters in a similar webapi service based on Kotlin and Spring Boot. It used registered converters and automatically performed the conversions in each direction. I'd really appreciate any nudges or suggestions on how to accomplish this task in Go.
Thank you for your time and interest, Mike
Solution 1:[1]
you can implement BSON interface
// bson/marshal.go
// Marshaler is an interface implemented by types that can marshal themselves
// into a BSON document represented as bytes. The bytes returned must be a valid
// BSON document if the error is nil.
type Marshaler interface {
MarshalBSON() ([]byte, error)
}
// bson/unmarshal.go
// Unmarshaler is an interface implemented by types that can unmarshal a BSON
// document representation of themselves. The BSON bytes can be assumed to be
// valid. UnmarshalBSON must copy the BSON bytes if it wishes to retain the data
// after returning.
type Unmarshaler interface {
UnmarshalBSON([]byte) error
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Edgar |
