0

Given the following struct...

package models

import (
    "time"
    "gopkg.in/mgo.v2/bson"
    "github.com/fatih/structs"
)

type User struct {
    Id         bson.ObjectId `json:"id,omitempty" bson:"_id,omitempty"`
    Name       string        `json:"name,omitempty" bson:"name,omitempty"`
    BirthDate  time.Time     `json:"birth_date,omitempty" bson:"birth_date,omitempty"`
}

... I fill it by parsing a HTTP request like this:

func (userController *UserController) UpdateUser() echo.HandlerFunc {
    return func(context echo.Context) error {
        user := &models.User{}

        // parse JSON in POST request and fill the User struct
        if err := context.Bind(user); err != nil {
            return err
        }

        // get user id from URL
        query := bson.M{"_id": bson.ObjectIdHex(context.Param("id"))}

        update := bson.M{
            // structs.Map() converts a User struct to a Map[string]interfacce{}
            "$set": structs.Map(user)
        }

        if err := userController.session.DB("test").C("users").Update(query, update); err !=   {
            return err
        }

        return context.JSON(http.StatusOK, user)
    }
}

The problem is that when I get an update JSON like this...

{
    "name": "Bon Scott",
    "birth_date" : "1946-07-09"
}

... structs.Map() still returns a Map that contains an empty id like this:

map[%!d(string=Name):%!d(string=Bon Scott) %!d(string=BirthDate):{63108633600 0 10736640} %!d(string=Id):%!d(bson.ObjectId=)]

I'd avoid creating the Map manually field-by-field like this:

update := bson.M{
    "name": user.Name,
    "birthDate": user.BirthDate,
}

Is there a way to strip out empty fields automatically?

j3d
  • 9,492
  • 22
  • 88
  • 172

1 Answers1

0

In your example, you are already using the ,omitempty tag in bson.

Based on the bson docs

omitempty Only include the field if it's not set to the zero value for the type or to empty slices or maps.

So, even if you pass the map directly to your update call, the empty fields should not be updated. The only issue should be, you should take care of the _id not being given an incorrect value.

Hugo
  • 254
  • 2
  • 6