首页 文章

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

提问于
浏览
0

我有以下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" }

Problem:

customer_id 是一个整数值, but 它将在数据库中保存为字符串 .

Possible workaround:

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

Question:

还有另一种保存数据的方法吗?例如 . 将整数值保存为整数值?

1 回答

  • 1

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

    您最终使用 string 类型的 customer_id 属性的原因是您保存的文档( conditions 变量)保存 customer_id 属性的 string 值 . 它的类型为 string ,因为您使用Context.PostForm()的返回值填充它,它返回一个表单值 string .

    如果您希望它是数据库中的整数,请在 conditions 中设置之前将其转换为Go整数 . 为此,您可以使用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
            }
        }
    }
    

    你必须以某种方式定义哪些字段应该包含整数值 . 我只是用一个字段展示了一种方法 . 如果你有多个,你可以在一个切片中列出它们,并使用一个 for 循环来检测/处理所有;甚至更好,将它们放在一个充当集合的 Map 中,你可以在没有 for 循环的情况下检测这些字段 .

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

相关问题