Custom BSON Marshaling
Custom BSON marshaling is similar to custom JSON marshaling, but you'll need to implement the bson.Getter and bson.Setter interfaces instead. These interfaces allow you to define how your custom type should be converted to and from BSON data.
For example, let's say you have a Currency type that requires custom marshaling:
package yourpackage import ( "context" "errors" "github.com/globalsign/mgo/bson" "github.com/shopspring/decimal" ) type Currency struct { Value decimal.Decimal CurrencyCode string } func (c Currency) GetBSON() (interface{}, error) { if c.CurrencyCode == "" { return nil, errors.New("CurrencyCode cannot be empty") } return bson.M{ "value": c.Value.String(), "currencyCode": c.CurrencyCode, }, nil } func (c *Currency) SetBSON(raw bson.Raw) error { var m bson.M if err := raw.Unmarshal(&m); err != nil { return err } val, ok := m["value"] if !ok { return errors.New("missing 'value' field in BSON data") } c.Value, _ = decimal.NewFromString(val.(string)) code, ok := m["currencyCode"] if !ok { return errors.New("missing 'currencyCode' field in BSON data") } c.CurrencyCode, _ = code.(string) return nil }
With this implementation, you can now register your custom Currency type with the MGO BSON encoder:
session := mgo.Dial("mongodb://localhost:27017") defer session.Close() session.SetCollectionValidator("products",{ "validator":{ "$jsonSchema":{ "bsonType":"object", "required":["name","code","price"], "properties":{ "name":{"bsonType":"string"}, "code":{"bsonType":"string"}, "price":{ "bsonType":"object", "required":["value", "currencyCode"], "properties":{ "value":{"bsonType":"string", "pattern":"^[0-9,]+(.[0-9,]+)?$"}, "currencyCode":{"bsonType":"string", "enum":["USD", "EUR", "GBP"]}, }, }, } } } }) collection := session.DB("products").C("products")
Now, when you save a document with a Currency field to MongoDB, the MGO encoder will automatically use your custom marshaling function to convert the Currency to BSON.
Note that this is just one example of how you can add custom marshaling for BSON types. The specific implementation will vary depending on the requirements of your particular application.
The above is the detailed content of How to Implement Custom BSON Marshaling in Go?. For more information, please follow other related articles on the PHP Chinese website!