3

I am running the below code. When a user saved in db then blank address is saved I have assigned the null struct to address before save. I can not add the omitempty with all the fields for address struct. How I can avoid to save blank address object within users collection

    package main

import (
    "context"
    "fmt"
    "time"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type User struct {
    Id          int           `json:"id" bson:"_id,omitempty"`
    FirstName   string        `json:"first_name,omitempty" bson:"first_name,omitempty"`
    LastName    string        `json:"last_name,omitempty" bson:"last_name,omitempty"`
    FullName    string        `json:"full_name,omitempty" bson:"full_name,omitempty"`
    CompanyName string        `json:"company_name" bson:"company_name"`
    Address     AddressStruct `json:"address,omitempty" bson:"address,omitempty"`
}
type AddressStruct struct {
    Address      string `json:"address" bson:"address"`
    City         string `json:"city" bson:"city"`
    State        string `json:"state" bson:"state"`
    Zipcode      string `json:"zipcode" bson:"zipcode"`
    Apt          string `json:"apt" bson:"apt"`
    Default      bool   `json:"default" bson:"default"`
    Status       int8   `json:"status,omitempty" bson:"status,omitempty"`
    Country      string `json:"country,omitempty" bson:"country,omitempty"`
    ShortAddress string `json:"short_address" bson:"short_address"`
}

func main() {
    var user User
    user.FirstName = "Swati"
    user.LastName = "Sharma"
    user.FullName = "Swati Sharma"
    user.Address = AddressStruct{}
    client, ctx := ConnectDbWithNewDriver()
    defer client.Disconnect(ctx)
    a, b := DbInsertOne(client, user)
    fmt.Println("Section1", a, b)
}
func ConnectDbWithNewDriver() (client *mongo.Client, ctx context.Context) {
    ctx = context.Background()
    client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://127.0.0.1:27017").SetConnectTimeout(5*time.Second))
    if err != nil {
        fmt.Println("CreateSession: ", err)
        client.Disconnect(ctx)
        return
    }
    return
}
func DbInsertOne(client *mongo.Client, data interface{}) (interface{}, error) {
    collection := client.Database("swatitest").Collection("users")
    insertResult, err := collection.InsertOne(context.TODO(), data)
    if err != nil {
        return nil, err
    }
    return insertResult.InsertedID, nil
}

When I run this code then record saved in db like this:

{
    "_id" : ObjectId("61af41b32214b16fe93435a6"),
    "first_name" : "Swati",
    "last_name" : "Sharma",
    "full_name" : "Swati Sharma",
    "company_name" : "",
    "address" : {
        "address" : "",
        "city" : "",
        "state" : "",
        "zipcode" : "",
        "apt" : "",
        "default" : false,
        "short_address" : ""
    }
}

I want to save like:

{
        "_id" : ObjectId("61af41b32214b16fe93435a6"),
        "first_name" : "Swati",
        "last_name" : "Sharma",
        "full_name" : "Swati Sharma",
        "company_name" : ""
}
6
  • You are using the omitempty option in the User struct, so you (or the person who wrote that code) must know about it. Use the omitempty in the AddressStruct too if you don't want empty strings get saved. Commented Dec 7, 2021 at 11:48
  • @icza Thanks. I have added the omitempty with address under user object its working fine but when I am using same code to save with mongodb new driver pkg "go.mongodb.org/mongo-driver/mongo" then its not working like that. Commented Dec 7, 2021 at 12:06
  • The official mongodriver also supports the omitempty option. Post a minimal reproducible example if it doesn't work for you. Commented Dec 7, 2021 at 12:10
  • @icza I have updated the code with new driver but it does not gives the required result. Commented Dec 7, 2021 at 12:25
  • The updated code does not have omitempty option for in the AddressStruct. For example if you don't want an empty city property, add omitempty to the AddressStruct.City field. Commented Dec 7, 2021 at 13:18

1 Answer 1

1

You may use the omitempty bson tag option, all Go drivers handle it and will not save the field if it's value is the zero value (for primitive types).

So add it to all fields you don't want to get saved as empty string:

type AddressStruct struct {
    Address      string `json:"address" bson:"address,omitempty"`
    City         string `json:"city" bson:"city,omitempty"`
    State        string `json:"state" bson:"state,omitempty"`
    Zipcode      string `json:"zipcode" bson:"zipcode,omitempty"`
    Apt          string `json:"apt" bson:"apt,omitempty"`
    Default      bool   `json:"default" bson:"default,omitempty"`
    Status       int8   `json:"status,omitempty" bson:"status,omitempty"`
    Country      string `json:"country,omitempty" bson:"country,omitempty"`
    ShortAddress string `json:"short_address" bson:"short_address,omitempty"`
}

If you can't modify the struct type, then don't save the struct value. Create your own type (where you add omitempty), copy the struct value into it, and save your own copy.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your and, but I can not add omitempty with each field of address. I have already mentioned that in the question. Is there another way to do this?
@Swati If you can't modify the struct type, then don't save the struct value. Create your own type (where you add omitempty), copy the struct value into it, and save your own copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.