Flatbson Save

Recursively flatten a Go struct using its BSON tags

Project README

FlatBSON

Build status API reference codecov

FlatBSON recursively flattens a Go struct using its BSON tags.

It is particularly useful for partially updating embedded Mongo documents.

For example, to update a User's Address.Visited field, first call flatbson.Flatten with the parent struct:

type User struct {
  ID      bson.ObjectID `bson:"_id,omitempty"`
  Name    string        `bson:"name,omitempty"`
  Address Address       `bson:"address,omitempty"`
}

type Address struct {
  Street    string    `bson:"street,omitempty"`
  City      string    `bson:"city,omitempty"`
  State     string    `bson:"state,omitempty"`
  VisitedAt time.Time `bson:"visitedAt,omitempty"`
}

flatbson.Flatten(User{Address: {VisitedAt: time.Now().UTC()}})

// Result:
// map[string]interface{}{"address.visitedAt": time.Time{...}}

Passing the result to coll.UpdateOne updates only the address.VisitedAt field instead of overwriting the entire address embedded document. See this blog post for more information.

The complete documentation is available on Godoc.

How to Install

go get -v github.com/chidiwilliams/flatbson
Open Source Agenda is not affiliated with "Flatbson" Project. README Source: chidiwilliams/flatbson
Stars
64
Open Issues
1
Last Commit
1 year ago
License
MIT

Open Source Agenda Badge

Open Source Agenda Rating