Golang MongoDB (MGO) Insert or read document field value is empty (nil) problem resolution

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Problem description

When using MgO operation MongoDB, encountered data insertion is normal, but in the database view can only see Objectid is inserted, read, you can query to the record, but when the object is read, but all the values are 0 or empty case.

MONGODB Document Structure:

{        "_id": ObjectId ("502fbbd6fec1300be858767e"),        "lastName": "Seba",        " FirstName ": June"        ,"inserted": Isodate ("2012-08-18t15:59:18.646z")}

Golang structure:

Type person struct {    _id         Bson. ObjectId    firstName  string    middlename string    lastName   string    inserted time   . TIME}

Reason

When you use interface-defined fields across packages, you have access only in one of two situations. (See Go language Specification)

exported identifiers

An identifier is exported to permit access to it from the 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 is not exported.

Solution Solutions

Capitalize the first letter of the object field. As shown below:

type person struct {    Id         Bson. ObjectId   "_id"    FirstName  string          "FirstName"    middlename string          " Middlename,omitempty "    LastName   string          " LastName "    Inserted time   . Time       "inserted"}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.