我在golang代码象下面这样:在数据库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以整数保存在数据库中的数据之前,1路。
是否存在另一种方式来保存数据,因为它是为提交(如保存为整数整数值)?
'c.PostForm(key)' - 这会返回什么类型? – zerkms
这将返回字符串值,即以字符串格式保存的方式。 – Swati
那么它不是“保存在数据库中的数据与golang不正确?”那么:-)这是你首先检索“不正确”的数据 – zerkms