将嵌套的结构体与MongoDB数据库进行映射,使用.Decode(&dto)方法。

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

Mapping a nested struct with mongo'd db .Decode(&dto)

问题

我有一个创建 JSON 文档的模型,没有问题,但是检索它时,嵌套的 JSON 对象为空。

func (r *CourseRepo) GetCourseById(ctx context.Context, id string) (Course, error) {
    clog := log.GetLoggerFromContext(ctx)

    var course Course

    objID, err := primitive.ObjectIDFromHex(id)
    if err != nil {
        return course, err
    }

    filter := bson.M{"_id": objID}

    err = r.collection.FindOne(ctx, filter).Decode(&course)
    if err != nil {
        clog.ErrorCtx(err, log.Ctx{"msg": "an error occurred while finding a course"})

        return course, err
    }

    return course, nil
}

结构体:

type Course struct {
    ObjectId    primitive.ObjectID `bson:"_id,omitempty"`
    Id          string             `json:"id"`
    Title       string             `json:"title"`
    Description string             `json:"description"`
    Lessons     string             `json:"lessons"`
    Duration    string             `json:"duration"`
    Details     struct {
        Title             string `json:"title"`
        Instructor        string `json:"instructor"`
        Introduction      string `json:"introduction"`
        Learn             string `json:"learn"`
        Topics            string `json:"topics"`
        Prerequisites     string `json:"prerequisites"`
        Goal              string `json:"goal"`
        AdditionalDetails string `json:"additionalDetails"`
        HighLevelOverview string `json:"highLevelOverview"`
    } `json:"course_details"`
}

结果:

{
    "data": {
        "ObjectId": "64953ac1bf06bfdd7936cad8",
        "id": "",
        "title": "Java Algorithms",
        "description": "An awesome course",
        "lessons": "4",
        "duration": "10 hours",
        "course_details": {
            "title": "",
            "instructor": "",
            "introduction": "",
            "learn": "",
            "topics": "",
            "prerequisites": "",
            "goal": "",
            "additionalDetails": "",
            "highLevelOverview": ""
        }
    },
    "metadata": "none"
}

根据我所了解的,.Decode 应该能够映射嵌套的值,对吗?

英文:

I have a model that creates a JSON document with no issue but retrieving it results in the nested JSON object being empty.

func (r *CourseRepo) GetCourseById(ctx context.Context, id string) (Course, error) {
	clog := log.GetLoggerFromContext(ctx)

	var course Course

	objID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return course, err
	}

	filter := bson.M{"_id": objID}

	err = r.collection.FindOne(ctx, filter).Decode(&course)
	if err != nil {
		clog.ErrorCtx(err, log.Ctx{"msg": "an error occurred while finding a course"})

		return course, err
	}

	return course, nil
}

Struct

type Course struct {
	ObjectId    primitive.ObjectID `bson:"_id, omitempty"`
	Id          string             `json:"id"`
	Title       string             `json:"title"`
	Description string             `json:"description"`
	Lessons     string             `json:"lessons"`
	Duration    string             `json:"duration"`
	Details     struct {
		Title             string `json:"title"`
		Instructor        string `json:"instructor"`
		Introduction      string `json:"introduction"`
		Learn             string `json:"learn"`
		Topics            string `json:"topics"`
		Prerequisites     string `json:"prerequisites"`
		Goal              string `json:"goal"`
		AdditionalDetails string `json:"additionalDetails"`
		HighLevelOverview string `json:"highLevelOverview"`
	} `json:"course_details"`
}

result

{
    "data": {
        "ObjectId": "64953ac1bf06bfdd7936cad8",
        "id": "",
        "title": "Java Algorithms",
        "description": "An awesome course",
        "lessons": "4",
        "duration": "10 hours",
        "course_details": {
            "title": "",
            "instructor": "",
            "introduction": "",
            "learn": "",
            "topics": "",
            "prerequisites": "",
            "goal": "",
            "additionalDetails": "",
            "highLevelOverview": ""
        }
    },
    "metadata": "none"
}

From what I read .Decode should map the nest values too?

答案1

得分: 2

JSON?但是Go MongoDB驱动程序与BSON一起工作

结构标签用于定义Go结构字段应如何映射到MongoDB文档字段。
在您的Course结构中,您使用了json标签,但是Go中的MongoDB驱动程序的Decode方法使用bson标签将文档字段映射到结构字段。

为了解决这个问题,您应该在结构字段中添加bson标签,包括嵌套结构,以指示MongoDB驱动程序如何将文档解码为您的结构。

type Course struct {
    ObjectId    primitive.ObjectID `bson:"_id,omitempty" json:"ObjectId"`
    Id          string             `bson:"id" json:"id"`
    Title       string             `bson:"title" json:"title"`
    Description string             `bson:"description" json:"description"`
    Lessons     string             `bson:"lessons" json:"lessons"`
    Duration    string             `bson:"duration" json:"duration"`
    Details     struct {
        Title             string `bson:"title" json:"title"`
        Instructor        string `bson:"instructor" json:"instructor"`
        Introduction      string `bson:"introduction" json:"introduction"`
        Learn             string `bson:"learn" json:"learn"`
        Topics            string `bson:"topics" json:"topics"`
        Prerequisites     string `bson:"prerequisites" json:"prerequisites"`
        Goal              string `bson:"goal" json:"goal"`
        AdditionalDetails string `bson:"additionalDetails" json:"additionalDetails"`
        HighLevelOverview string `bson:"highLevelOverview" json:"highLevelOverview"`
    } `bson:"course_details" json:"course_details"`
}

请注意,您可以在同一个字段上同时使用bsonjson标签。bson标签在与MongoDB交互时使用(例如,调用.Decode()时),而json标签在JSON格式的编组/解组时使用。

此外,请确保bson标签中的字段名称与MongoDB文档中的字段名称匹配。例如,如果MongoDB文档中的字段名为courseDetails而不是course_details,则应将bson标签更改为bson:"courseDetails"

英文:

JSON? But the Go MongoDB driver works with BSON

The struct tags are used to define how the Go struct fields should be mapped to the MongoDB document fields.
In your Course struct, you are using json tags, but the Decode method from the MongoDB driver in Go uses the bson tags to map the document fields to the struct fields.

To solve this issue, you should add bson tags to your struct fields, including the nested struct, to instruct the MongoDB driver how to decode the document into your struct.

type Course struct {
    ObjectId    primitive.ObjectID `bson:"_id,omitempty" json:"ObjectId"`
    Id          string             `bson:"id" json:"id"`
    Title       string             `bson:"title" json:"title"`
    Description string             `bson:"description" json:"description"`
    Lessons     string             `bson:"lessons" json:"lessons"`
    Duration    string             `bson:"duration" json:"duration"`
    Details     struct {
        Title             string `bson:"title" json:"title"`
        Instructor        string `bson:"instructor" json:"instructor"`
        Introduction      string `bson:"introduction" json:"introduction"`
        Learn             string `bson:"learn" json:"learn"`
        Topics            string `bson:"topics" json:"topics"`
        Prerequisites     string `bson:"prerequisites" json:"prerequisites"`
        Goal              string `bson:"goal" json:"goal"`
        AdditionalDetails string `bson:"additionalDetails" json:"additionalDetails"`
        HighLevelOverview string `bson:"highLevelOverview" json:"highLevelOverview"`
    } `bson:"course_details" json:"course_details"`
}

Note that you can have both bson and json tags on the same field. The bson tags are used when interacting with MongoDB (e.g., when calling .Decode()), and the json tags are used when marshaling/unmarshaling to/from JSON format.

Also, make sure that the field names in your bson tags match the field names in your MongoDB documents. For example, if the field in the MongoDB document is named courseDetails instead of course_details, you should change the bson tag to bson:"courseDetails".

huangapple
  • 本文由 发表于 2023年6月23日 16:35:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76538379.html
匿名

发表评论

匿名网友

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

确定