0
我試圖編組一個結構到JSON,然後將其插入到我的Mongo數據庫,但繼續得到這個錯誤:%!(EXTRA main.Test={575590180 Me})
。我做錯了什麼?我把這段代碼完全從另一個。項目我從事這可能插入文檔沒有任何問題Golang Mongodb%(額外
package main
import (
"utils"
"hash/fnv"
"log"
"gopkg.in/mgo.v2"
"encoding/json"
)
type Test struct {
Id uint32
Name string
}
func ConnectDB() *mgo.Session {
session, err := mgo.Dial("localhost:27017")
if err != nil {
panic(err)
}
return session
}
func SaveMgoDoc(dbName string, collectionName string, file Test) bool {
session, err := mgo.Dial("localhost:27017")
if err != nil {
panic(err)
}
defer session.Close()
fileJson, err := json.Marshal(file)
if err != nil {
log.Printf("failed to marshal struct to json...\n", file)
return false
}
collection := session.DB(dbName).C(collectionName)
err = collection.Insert(&fileJson)
if err != nil {
log.Printf("failed to insert doc into database...\n", file)
return false
}
return true
}
func hash(s string) uint32 {
h := fnv.New32a()
h.Write([]byte(s))
return h.Sum32()
}
func main() {
utils.SaveMgoDoc("mydb", "mydoc", Test{hash("Me"), "Me"})
}
@old_mountain那對於愚蠢的問題抱歉,我假設所有對象都是m最好是將JSON插入到MongoDB中。謝謝! – Soubriquet