我有以下 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
回整数。
问题:
是否有另一种方法可以按原样保存数据?例如将整数值保存为整数值?