markz
markz

Reputation: 1766

Empty properties when serializing MongoDB data in Go

This might be a very silly problem, but after two hours of searching the net I am posting the question here.

I tried learning Go and have a very simple "Hello World" application, which uses Mongo for the data source. I can connect normally, I can fetch the data, and the count of objects turns out ok.

The problem is, the object I map data to has empty properties, although there is data in Mongo.

I have a very simple collection in mongo, called stations with ~12k records like these:

{ "_id" : ObjectId("563c8d56819c3c91076b7c13"), "nm" : "00000BE8" }
{ "_id" : ObjectId("563c8d57819c3c91076b7c1a"), "nm" : "00000C01" }
{ "_id" : ObjectId("563c8d58819c3c91076b7c1d"), "nm" : "00000C02" }
{ "_id" : ObjectId("563c8d58819c3c91076b7c1f"), "nm" : "00000C31" }
{ "_id" : ObjectId("563c8d5d819c3c91076b86c1"), "nm" : "000013E0" }
{ "_id" : ObjectId("563c8d5d819c3c91076b86c5"), "nm" : "0000110B" }

The entire Go program looks like this:

package main

import (
    "log"
    "gopkg.in/mgo.v2"
)

type StationConfig struct {
        id     string   `bson:"_id,omitempty"`
        name   string   `bson:"nm"`
}

func main() {
        session, err := mgo.Dial("192.168.1.41")
        if err != nil {
                panic(err)
        }
        defer session.Close()

        c := session.DB("metos").C("stations")

        var stationConfigs []StationConfig            
        err = c.Find(nil).Limit(100).All(&stationConfigs)

        if err != nil {
                log.Fatal(err)
        }

        log.Printf("Found document: %+v\n", stationConfigs)
}

But when I run the program, the values of _id and nm are not assigned to the respective struct properties and I get the following output:

Found document: [{id: name:} {id: name:} {id: name:} {id: name:} 
    {id: name:} {id: name:} {id: name:} {id: name:} {id: name:} 
    {id: name:} {id: name:} {id: name:} {id: name:} {id: name:} 
    {id: name:} {id: name:} {id: name:} {id: name:} {id: name:} 
    {id: name:} {id: name:} {id: name:} ... and so on ... ]

What am I missing?

Upvotes: 2

Views: 213

Answers (1)

vially
vially

Reputation: 1516

I'm not familiar with the MongoDB Go API but I think your struct fields should be public in order for the MongoDB API to be able to populate them.

Try making your fields public and see if it works:

type StationConfig struct {
        ID     string   `bson:"_id,omitempty"`
        Name   string   `bson:"nm"`
}

Upvotes: 1

Related Questions