避免将空的结构对象保存在数据库中。

huangapple go评论142阅读模式
英文:

Avoid to save blank struct object in db

问题

我正在运行以下代码。当用户保存在数据库中时,空地址被保存了,我在保存之前将地址字段赋值为null结构体。我不能在地址结构体的所有字段上添加omitempty。我该如何避免在用户集合中保存空地址对象?

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
}

当我运行这段代码时,记录在数据库中保存如下:

{
	"_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" : ""
	}
}

我希望保存的结果如下:

{
	"_id" : ObjectId("61af41b32214b16fe93435a6"),
	"first_name" : "Swati",
	"last_name" : "Sharma",
	"full_name" : "Swati Sharma",
	"company_name" : ""
}
英文:

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" : ""
}

答案1

得分: 1

你可以使用omitempty bson标签选项,所有的Go驱动程序都会处理它,并且如果字段的值是零值(对于原始类型),它们将不会保存该字段。

因此,将它添加到所有你不希望保存为空字符串的字段中:

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"`
}

如果你无法修改结构体类型,那么就不要保存结构体值。创建自己的类型(在其中添加omitempty),将结构体值复制到其中,并保存你自己的副本。

英文:

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.

huangapple
  • 本文由 发表于 2021年12月7日 19:42:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/70259520.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定