dsvyc66464 2015-11-17 17:27
浏览 103
已采纳

在Go中序列化MongoDB数据时的空属性

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
", 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?

  • 写回答

1条回答 默认 最新

  • dongtaotao19830418 2015-11-17 17:43
    关注

    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"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器