I've the following golang code:
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
", err)
}
mongoSession.SetMode(mgo.Monotonic, true)
return mongoSession
}
When I run the code, data of the following format will be saved in the database:
{ "_id" : 1, "customer_id" : "3", "address" : "Chicago, IL", "city" : "Chicago", "state" : "IL", "zipcode" : "60647" }
Problem:
customer_id
is an integer value, but it will be saved as string in the database.
Possible workaround:
It is possible to reconvert the string representation of id
back to integer before saving it in the database.
Question:
Is there another way to save data as it is? E.g. to save integer values as integer values?