无法使用Golang将结构保存到MongoDB(只创建空记录)

huangapple go评论92阅读模式
英文:

Cannot save structure into mongodb with golang (only empty records created)

问题

我有以下的结构体:

type Result struct {
    nid         string
    timestamp   int64
    hexhash     string
    addr        string
}

我想将它保存到 MongoDB 中:

我创建了一个实例:

r := Result{hex_id, int64(msg.timestamp.Unix()), hexhash, msg.addr.String()}

并测试是否正确创建:

fmt.Println(r)

这给出了我期望的结果:

{b8da3f19d1318af6879976c1eea66c78c48e1144 1421417252 65072917F19D7F4C4B54C9C66A3EB31F77012981 127.0.0.1:65290}

然后我将其保存到 MongoDB 中:

h.c.Insert(r)

但在 MongoDB 中,我只看到空记录:

db.data.find()
{ "_id" : ObjectId("54b91a268da6c829a412cd4d") }

上面代码中的 h 定义如下:

type Handler struct {
    storage     map[string]Message
    new_msg     chan Message
    new_inp     chan Input
    c           *mgo.Collection
}

h.c = session.DB(DATABASE).C(COLLECTION)

希望这能帮到你!

英文:

I have the following structure

type Result struct {
    nid         string
    timestamp   int64
    hexhash     string
    addr        string
}

which I want to save into mongodb:

I create it

r := Result{hex_id, int64(msg.timestamp.Unix()), hexhash, msg.addr.String()}

And test if it is created correctly:

fmt.Println(r) 

Which gives me result I'm expecting:

> {b8da3f19d1318af6879976c1eea66c78c48e1144 1421417252
> 65072917F19D7F4C4B54C9C66A3EB31F77012981 127.0.0.1:65290}

Then I save it into mongo:

h.c.Insert(r)

But in mongo i see only empty records:

> db.data.find()

> { "_id" : ObjectId("54b91a268da6c829a412cd4d") }

The h in the code above defined as

type Handler struct {
    storage     map[string]Message
    new_msg     chan Message
    new_inp     chan Input
    c           *mgo.Collection
}

and

h.c = session.DB(DATABASE).C(COLLECTION)

答案1

得分: 2

你的记录字段需要对其他包(如MongoDB包装器)公开才能让它们看到。将字段重命名为以下形式:

type Result struct {
    Nid         string
    Timestamp   int64
    Hexhash     string
    Addr        string
}
英文:

The fileds of your record need to be public for other packages (like the MongoDB wrapper) to see them. Rename the fields like this:

type Result struct {
    Nid         string
    Timestamp   int64
    Hexhash     string
    Addr        string
}

huangapple
  • 本文由 发表于 2015年1月16日 22:22:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/27986011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定