Home > Mobile >  how to change the values of an array to an empty string or an empty array in golang?
how to change the values of an array to an empty string or an empty array in golang?

Time:11-22

i have code which contains some nested array values. as follows:

   `
    var descriptor models.Descriptor
    _ = json.NewDecoder(r.Body).Decode(&descriptor)
    result, _ := collectionDescriptor.InsertOne(context.TODO(), descriptor)

type Descriptor struct {
    Id      string `json:"id" bson:"id"`
    Type    string `json:"type,omitempty" bson:"type,omitempty"`
    Name    string `json:"name,omitempty" bson:"name,omitempty"`
    Version string `json:"version,omitempty" bson:"version,omitempty"`
    Modules []string `json:"modules,omitempty" bson:"modules,omitempty"`
    Configs []Config `json:"configs" bson:"configs"`
    
}
type Config struct {
    Id       string `json:"id" bson:"id"`
    Type     string `json:"type,omitempty" bson:"type,omitempty"`
    Name     string `json:"name,omitempty" bson:"name,omitempty"`
    Protocol []Protocols `json:"protocol" bson:"protocol"`
}
type Protocols struct {
    Id    string `json:"id" bson:"id"`
    Type  string `json:"type,omitempty" bson:"type,omitempty"`
    Name  string `json:"name" bson:"name,omitempty"`
    Items []Itemes `json:"items" bson:"items"`
}

descriptor.Configs[0].Protocol[0] = nil

config = descriptor.Configs[0]
_ = json.NewDecoder(r.Body).Decode(&config)

conf, errr := collectionConfigDes.InsertOne(context.TODO(), config)
json.NewEncoder(w).Encode(conf)`

I want to remove the value in descriptor.configs[0].protocol to be an empty array or an empty string. which I will then send to mongoDB. json form like below

enter image description here enter image description here

Different approaches (on JSON) are,

1.1. Remove omitempty from Protocol field. This gives null in JSON.

Protocol []Protocols `json:"protocol" bson:"protocol"`

1.2. Remove omitempty like above; and use make as @Sangria mentioned. This gives empty array/slice in JSON.

desc[0].Configs[0].Protocol = make([]Protocols, 0)
Null Value Empty Array
enter image description here enter image description here

This works for JSON at least. Is there any issue to insert the same into Mongo? Try the 3 possibilities.

  1. Doesn't matter if you are storing the record as a new one. But in case of editing the existing, you should be using collection.UpdateOne() in Mongo.
  • Related