-1

I have a structure like this:

type Document struct {
    ID          primitive.ObjectID  `bson:"_id,omitempty"`
    description string              `bson:"description,omitempty"`
}

And I have the getter for description field:

func (d *Document) Description() string {
    strip := bluemonday.StripTagsPolicy()
    return strip.Sanitize(d.description)
}

But when I try to save the document to the MongoDb it ignores description field:

func (d *Document) SaveMongo() (*mongo.InsertOneResult, error) {
   insertResult, err := App.MongoCollection.InsertOne(context.Background(), d)
   ...
}

How can I save private field using getter?

Bookin
  • 282
  • 2
  • 16

1 Answers1

0

Drivers don't look for "getters". You have to export the fields you want to store in the DB.

Alternatively you could create a custom marshaler which also saves the unexported fields, but it's much simpler to just export them. An example would be to create a version of your struct with exported fields or a map, and call the default marshaling logic on that value.

icza
  • 389,944
  • 63
  • 907
  • 827
  • If possible could you please provide any examples? What means much simpler if I need to do something with data before returning them? I didn't want duplicate structure it reason why I am looking for another way – Bookin Mar 04 '21 at 19:52
  • @Bookin You don't want it but that's the simplest solution. If you want your life to be easy, export the field or create another struct where it is exported and marshal that. – icza Mar 04 '21 at 20:10