2014-04-08 20 views
1

我在我的項目中使用Go和mongoDB,mgo是連接到MongoDB如何構建並傳遞bson文檔 - Go lang?

我有以下文件這是在MongoDB的

{ 
    "_id" : ObjectId("53439d6b89e4d7ca240668e5"), 
    "balanceamount" : 3, 
    "type" : "reg", 
    "authentication" : { 
     "authmode" : "10", 
     "authval" : "sd", 
     "recovery" : { 
      "mobile" : "sdfsd", 
      "email" : "[email protected]" 
     } 
     }, 
    "stamps" : { 
     "in" : "x", 
     "up" : "y" 
    } 
    } 

我已經創建與上述BSON文件插入。

我有兩個包

  1. account.go

  2. dbEngine.go

account.go用於創建文檔BSON併發送BSON文檔dbEngine.go

dbEngine.go用於建立到MongoDB的連接並插入文檔。 同時將BSON文件傳遞給dbEngine.go

dbEngine.Insert(bsonDocument);

在dbEngine.go我有方法

func Insert(document interface{}){ 
//stuff 
} 

錯誤:恐慌:無法編組接口{}爲BSON文檔。

BSON文檔中是否不使用接口{}。

我是Go的新手。任何建議或幫助將不勝感激

回答

1

你不需要自己生成一個BSON文件。
讓account.go說你有一個帳戶結構:

type Account struct { 
    Id bson.ObjectId `bson:"_id"` // import "labix.org/v2/mgo/bson" 
    BalanceAmount int 
    // Other field 
} 

然後在dbEngine.go您插入功能:

func Insert(document interface{}){ 
    session, err := mgo.Dial("localhost") 
    // check error 
    c := session.DB("db_name").C("collection_name") 
    err := c.Insert(document) 
} 

,然後在你的應用中的一些地方:

acc := Account{} 
acc.Id = bson.NewObjectId() 
acc.BalanceAmount = 3 

dbEngine.Insert(&acc); 
1

mgo驅動程序使用labix.org/v2/mgo/bson包來處理BSON編碼/解碼。大多數情況下,該軟件包是在標準庫encoding/json包後建模的。

所以你可以使用結構體和數組來表示對象。例如,

type Document struct { 
    Id bson.ObjectId `bson:"_id"` 
    BalanceAmount int `bson:"balanceamount"` 
    Type string `bson:"type"` 
    Authentication Authentication `bson:"authentication"` 
    Stamps Stamps `bson:"stamps"` 
} 
type Authentication struct { 
    ... 
} 
type Stamps struct { 
    ... 
} 

您現在可以創建此類型的值以傳遞到mgo