這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
問題描述
當使用mgo操作mongodb時,遇到資料插入正常,但是在資料庫查看時只能看到objectid被插入了;讀取的時候,可以查詢到記錄,但是讀入對象時,卻所有的值均為0或者空的情況。
mongodb文檔結構:
{ "_id" : ObjectId("502fbbd6fec1300be858767e"), "lastName" : "Seba", "firstName" : "Jun", "inserted" : ISODate("2012-08-18T15:59:18.646Z")}
golang結構:
type Person struct { _id bson.ObjectId firstName string middleName string lastName string inserted time.Time}
原因
當跨包使用interface定義的欄位時,只有一下兩種情形,才擁有存取權限。(詳見go語言規範)
Exported identifiers
An identifier may be exported to permit access to it from another package. An identifier is exported if both:
- the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
- the identifier is declared in the package block or it is a field name or method name.
All other identifiers are not exported.
解決方案
將對象欄位的首字母大寫。如下所示:
type Person struct { Id bson.ObjectId "_id" FirstName string "firstName" MiddleName string "middleName,omitempty" LastName string "lastName" Inserted time.Time "inserted"}