golang mongodb (mgo)插入或讀取文檔的欄位值為空白(nil)問題解決

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

問題描述

當使用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:

  1. the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and
  2. 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"}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.