go - 在数据库 golang 中保存发布数据(具有整数和字符串值)的正确方法是什么?

标签 go mgo go-gin

我有以下 golang 代码:

package main

import (
    "github.com/gin-gonic/gin"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
    "log"
    "time"
)

func main() {
    router := gin.Default()
    router.POST("/save-address", SaveAddress)
    router.Run()
}

func SaveAddress(c *gin.Context){
    var err error
    conditions := bson.M{}
    c.Request.ParseForm()
    for key, _ := range c.Request.PostForm {
        if key != "id"{
            conditions[key] = c.PostForm(key)
        }
    }
    conditions["_id"] = 1
    mongoSession := ConnectDb()

    sessionCopy := mongoSession.Copy()
    defer sessionCopy.Close()

    getCollection := mongoSession.DB("bformssettings").C("address")
    err = getCollection.Insert(conditions)
    if err != nil{
        println(err)
    }else{
        println("Data saved successfully!!!")
    }
}
func ConnectDb() (mongoSession *mgo.Session) {
    mongoDBDialInfo := &mgo.DialInfo{
        Addrs:    []string{"localhost:27017"},
        Timeout:  60 * time.Second,
        Database: "bformssettings",
    }

    mongoSession, err := mgo.DialWithInfo(mongoDBDialInfo)
    if err != nil {
        log.Fatalf("CreateSession: %s\n", err)
    }

    mongoSession.SetMode(mgo.Monotonic, true)

    return mongoSession
}

当我运行代码时,数据库中会保存如下格式的数据:

{ "_id" : 1, "customer_id" : "3", "address" : "Chicago, IL", "city" : "Chicago", "state" : "IL", "zipcode" : "60647" }

问题:

customer_id 是一个整数值,但是它会在数据库中保存为字符串。

可能的解决方法:

在将 id 的字符串表示形式保存到数据库之前,可以将其重新转换回整数。

问题:

还有其他方法可以原封不动地保存数据吗?例如。将整数值保存为整数值?

最佳答案

如果您查看保存的文档,您会发现它的 _id 属性已经是一个数字(而不是字符串),所以是的,这绝对是可能的。

你最终得到 customer_id 类型为 string 的原因是因为你保存的文档(conditions 变量)包含一个customer_id 属性的 string 值。它是 string 类型,因为你用 Context.PostForm() 的返回值填充了它它以 string 的形式返回表单值。

如果您希望它是数据库中的整数,请将其转换为 Go 整数,然后再将其设置为 conditions。为此,您可以使用 strconv.Atoi()例如。

for key, _ := range c.Request.PostForm {
    value := c.PostForm(key)
    if key == "customer_id" {
        if id, err := strconv.Atoi(value); err != nil {
            // Not a valid number, handle error
        } else {
            conditions[key] = id
        }
    } else {
        if key != "id"{
            conditions[key] = value
        }
    }
}

您必须以某种方式定义哪些字段应该保存整数值。我只是展示了一种使用单个字段执行此操作的方法。如果你有多个,你可以将它们列在一个 slice 中,并使用单个 for 循环来检测/处理所有;甚至更好的是,将它们放在一个充当集合的 map 中,您可以在没有 for 循环的情况下检测这些字段。

另一种选择是创建一个struct 类型来建模您的表单输入数据,并使用像Gorilla's schema 这样的库。以类型感知的方式解码到该结构中。

关于go - 在数据库 golang 中保存发布数据(具有整数和字符串值)的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45690659/

相关文章:

go - 如何在 Golang 中快速找到接口(interface)的实现?

json - Golang map : How to strip out empty fields automatically

unit-testing - 如何发送POST请求的multipart/form-data字段作为数组进行单元测试?

mongodb - 我怎么知道 mgo session 是否关闭

go - 如何绑定(bind)到 go (gin) 形式的 slice 值?

go - 如何解码 map[string]interface 类型的 Go struct 字段

reactjs - axios.post请求获取404

GoLang 附加到嵌套 slice

go - 我如何在 Go 中对接口(interface) slice 进行 json 解码?

Golang 中的 Javascript toISOString 时间