Table of Contents
Question content
Solution
Home Backend Development Golang Use mongo'd db .Decode(&dto) to map nested structures

Use mongo'd db .Decode(&dto) to map nested structures

Feb 09, 2024 am 11:51 AM

使用 mongo\'d db .Decode(&dto) 映射嵌套结构

php editor Zimo today introduces a method of using mongo'd db .Decode(&dto) to map nested structures. During the development process, we often encounter situations where we need to decode and map nested structures from the database into the corresponding data transfer objects (DTO). The Decode function of mongo'db can help us simplify this process. We only need to pass in the structure to be decoded and the target DTO object, and the decoding and mapping can be automatically performed. This method is simple and efficient, and can greatly improve development efficiency. Next, we will introduce in detail how to use this method to implement the mapping of nested structures.

Question content

I have a model that creates a json document without issue, but retrieving it results in the nested json object being empty.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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

}

Copy after login

Structure

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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"`

}

Copy after login

result

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

{

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

}

Copy after login

From what I've read, should decode map nested values ​​as well?

Solution

json? But go mongodb driver works with bson

The structure tag is used to define how go structure fields should be mapped to mongodb document fields.
In the course structure you use the json tag, but the decode method maps the document fields using the bson tag to the structure field.

To resolve this issue, you should add the bson tag to your struct fields (including nested structs) to instruct the mongodb driver how to decode the document into your struct.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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"`

}

Copy after login

Note that you can have both bson and json tags on the same field. The bson tag is used when interacting with mongodb (for example, when calling .decode()), while the json tag is used when marshalling/unmarshaling to json format use.

Additionally, make sure that the field names in the bson tag match the field names in the mongodb document. For example, if the field in the mongodb document is named coursedetails instead of course_details, then the bson tag should be changed to bson:"coursedetails".

The above is the detailed content of Use mongo'd db .Decode(&dto) to map nested structures. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Go language pack import: What is the difference between underscore and without underscore? Go language pack import: What is the difference between underscore and without underscore? Mar 03, 2025 pm 05:17 PM

Go language pack import: What is the difference between underscore and without underscore?

How do I write mock objects and stubs for testing in Go? How do I write mock objects and stubs for testing in Go? Mar 10, 2025 pm 05:38 PM

How do I write mock objects and stubs for testing in Go?

How to implement short-term information transfer between pages in the Beego framework? How to implement short-term information transfer between pages in the Beego framework? Mar 03, 2025 pm 05:22 PM

How to implement short-term information transfer between pages in the Beego framework?

How can I use tracing tools to understand the execution flow of my Go applications? How can I use tracing tools to understand the execution flow of my Go applications? Mar 10, 2025 pm 05:36 PM

How can I use tracing tools to understand the execution flow of my Go applications?

How can I define custom type constraints for generics in Go? How can I define custom type constraints for generics in Go? Mar 10, 2025 pm 03:20 PM

How can I define custom type constraints for generics in Go?

How to write files in Go language conveniently? How to write files in Go language conveniently? Mar 03, 2025 pm 05:15 PM

How to write files in Go language conveniently?

How to convert MySQL query result List into a custom structure slice in Go language? How to convert MySQL query result List into a custom structure slice in Go language? Mar 03, 2025 pm 05:18 PM

How to convert MySQL query result List into a custom structure slice in Go language?

How do I write benchmarks that accurately reflect real-world performance in Go? How do I write benchmarks that accurately reflect real-world performance in Go? Mar 10, 2025 pm 05:36 PM

How do I write benchmarks that accurately reflect real-world performance in Go?

See all articles