retrieve a nested document with mgo

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

retrieve a nested document with mgo

问题

我需要使用mgo从MongoDB中检索一个嵌套文档。以下是我的数据库中的文档:

{
    "_id" : "packing_type_0000",
    "name" : "packing",
    "category" : "logistics",
    "en" : {
        "translatedName" : "Packing and Order Prep"
    }
}

这是我的Golang结构体:

type jobTypeWording struct {
    TranslatedName string `json:"translatedName" bson:"translatedName"`
}

type jobType struct {
    ID       string       `json:"_id" bson:"_id"`
    Name     string       `json:"name" bson:"name"`
    Category string       `json:"category" bson:"category"`
    En       jobTypeWording `json:"en" bson:"en"`
}

这是我的代码:

result := jobType{}
sessionCopy := session.Copy()
defer sessionCopy.Close()
c := sessionCopy.DB(os.Getenv("DB_DATABASE")).C("jobTypes")
err := c.Find(bson.M{"_id": Id}).One(&result)
fmt.Println(result.En.TranslatedName)

我的程序输出:

Packing and Order Prep

如何检索en.translatedName?在同一个程序中,我以相同的方式获取其他嵌套的bson,并且可以正常工作。我不明白我的错误在哪里。

英文:

I need to retrieve a nested document in mongoDB with mgo.
Here is my document in db:

{
    "_id" : "packing_type_0000",
    "name" : "packing",
    "category" : "logistics",
    "en" : {
            "translatedName" : "Packing and Order Prep",
    },
}

This is my golang structure:

type jobTypeWording struct {
     translatedName     string `json:"translatedName" bson:"translatedName"`
}

type jobType struct {
    ID               string         `json:"_id" bson:"_id"`
    Name             string         `json:"name" bson:"name"`
    Category         string         `json:"category" bson:"category"`
    en               jobTypeWording `json:"en" bson:"en"`
}

And my code:

result := jobType{}
sessionCopy := session.Copy()
defer sessionCopy.Close()
c := sessionCopy.DB(os.Getenv("DB_DATABASE")).C("jobTypes")
err := c.Find(bson.M{"_id": Id}).One(&result)  
fmt.Println(result.en)

My program program output:

{  }

How do I retrieve en.translatedName?

In the same program I get other nested bson from mongo and it's working with same way. I don't understand my mistake.

答案1

得分: 1

我找到了解决方案,原因是我的字段 en 以小写字母开头。如果我将 en 改为 En,将 translatedName 改为 TranslatedName,它就可以工作了。更多详细信息请参考答案

英文:

I found solution, it's because my field en began by a lower case. If i change en by En and translatedName by TranslatedName , it's work.
Here a more details answer

huangapple
  • 本文由 发表于 2017年4月28日 18:04:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/43677530.html
匿名

发表评论

匿名网友

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

确定