在Golang中,儲存資料到MongoDB時,常常會遇到空資料值的問題。當某個欄位的值為空時,MongoDB預設會將其儲存為null。然而,在實際應用中,我們可能更希望將其儲存為特定的預設值,以便更好地處理和查詢資料。那麼,在Golang中如何解決這個問題呢?本文將由php小編百草為您詳細解答。
問題內容
我是 Golang 的新手,我遇到了將資料儲存到資料庫的問題。從 API 接收到 JSON 物件後,我嘗試將其儲存在 MongoDB 中,但資料以空值保存。
這是我的程式碼和結構:
var current:={ "usd": { "code": "USD", "alphaCode": "USD", "numericCode": "840", "name": "U.S. Dollar", "rate": 0.68135437808647, "date": "Sun, 31 Dec 2023 11:55:01 GMT", "inverseRate": 1.4676650391657 }, "eur": { "code": "EUR", "alphaCode": "EUR", "numericCode": "978", "name": "Euro", "rate": 0.61624276207684, "date": "Sun, 31 Dec 2023 11:55:01 GMT", "inverseRate": 1.6227371119619 }, "gbp": { "code": "GBP", "alphaCode": "GBP", "numericCode": "826", "name": "U.K. Pound Sterling", "rate": 0.53541690218052, "date": "Sun, 31 Dec 2023 11:55:01 GMT", "inverseRate": 1.8677034586085 } }
這是我的 model.go
type Currency struct { Code string `json:"code"` AlphaCode string `json:"alphaCode"` NumericCode string `json:"numericCode"` Name string `json:"name"` Rate float64 `json:"rate"` Date string `json:"date"` InverseRate float64 `json:"inverseRate"` } type Rate struct { ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"` Currency `json:"currency"` Timestamp primitive.DateTime `json:"timestamp"` }
我嘗試將資料儲存到資料庫,但我只寫入帶有空字串和 0 的預設值
const apiUrl = "https://www.floatrates.com/daily/aud.json" func GetRatesFromAPI() (map[string]models.Rate, error) { response, err := http.Get(apiUrl) fmt.Print(response) if err != nil { return nil, err } defer response.Body.Close() body, err := ioutil.ReadAll(response.Body) if err != nil { return nil, err } var data map[string]models.Rate if err := json.Unmarshal(body, &data); err != nil { return nil, err } fmt.Print(data) return data, nil } r.GET("/get", func(c *gin.Context) { mongo.ConnectDB() rates, err := src.GetRatesFromAPI() fmt.Print(rates) if err != nil { log.Fatal(err) } for _, rate := range rates { mongo.InsertRate(rate) } c.String(http.StatusOK, "get rates") }) func InsertRate(rate models.Rate) { rate.Timestamp = primitive.NewDateTimeFromTime(time.Now()) collection := client.Database("mongodb").Collection("rates") ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() result, err := collection.InsertOne(ctx, rate) if err != nil { log.Fatal(err) } log.Println("Inserted rate with ID:", result.InsertedID) }
我在資料庫中得到這個對象,但沒有任何值,我試圖找出為什麼資料沒有正確儲存在 MongoDB 中。任何幫助或建議將不勝感激!
[ { "_id": {"$oid": "659177abefa699e213158c16"}, "currency": { "code": "", "alphacode": "", "numericcode": "", "name": "", "rate": 0, "date": "", "inverserate": 0 }, "timestamp": {"$date": "2023-12-31T14:16:11.800Z"} } ]
解決方法
問題是由於使用json 標籤json:"currency"
在Rate
類型中嵌入Currency
類型而引起的。但是,為 json.Unmarshal
提供的輸入 JSON 不包含對應的「Currency
」欄位。因此,Currency
類型中的所有欄位都會接收零值,然後將其儲存在 MongoDB 中。為了解決這個問題,您可以在嵌入Currency
類型期間消除json 標籤json:"currency"
(如下所示),或者建立目標物件以與輸入JSON 的結構保持一致。
type Rate struct { ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"` Currency Timestamp primitive.DateTime `json:"timestamp"` }
以上是在 Golang 中儲存到 MongoDB 時如何解決空資料值問題?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可維護,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增強ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口進行模擬和測試的原因是:接口允許定義合同而不指定實現方式,使得測試更加隔離和易於維護。 1)接口的隱式實現使創建模擬對像變得簡單,這些對像在測試中可以替代真實實現。 2)使用接口可以輕鬆地在單元測試中替換服務的真實實現,降低測試複雜性和時間。 3)接口提供的靈活性使得可以為不同測試用例更改模擬行為。 4)接口有助於從一開始就設計可測試的代碼,提高代碼的模塊化和可維護性。

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3漢化版
中文版,非常好用

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

WebStorm Mac版
好用的JavaScript開發工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。