flatbson

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 22, 2020 License: MIT Imports: 5 Imported by: 8

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 https://github.com/chidiwilliams/flatbson

Documentation

Overview

Package flatbson provides a function for recursively flattening a Go struct using its BSON tags.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Flatten

func Flatten(v interface{}) (map[string]interface{}, error)

Flatten returns a map with keys and values corresponding to the field name and values of struct v and its nested structs according to its BSON tags. It iterates over each field recursively and sets fields that are not nil.

The BSON struct tags behave in line with the bsoncodec specification. See: https://godoc.org/go.mongodb.org/mongo-driver/bson/bsoncodec#StructTags for definitions. The supported tags are name, skip, omitempty, and inline.

Flatten does not flatten structs with unexported fields, e.g. time.Time. It returns an error if v is not a struct or a pointer to a struct, or if the tags produce duplicate keys.

type A struct {
  B *X `bson:"b,omitempty"`
  C X  `bson:"c"`
}

type X struct { Y string `bson:"y"` }

Flatten(A{nil, X{"hello"}})
// Returns:
// map[string]interface{}{"c.y": "hello"}

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL