目錄
問題內容
解決方法
首頁 後端開發 Golang 使用 mongo'd db .Decode(&dto) 來映射巢狀結構

使用 mongo'd db .Decode(&dto) 來映射巢狀結構

Feb 09, 2024 am 11:51 AM

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

php小編子墨今天為大家介紹一個使用mongo'd db .Decode(&dto)來對應巢狀結構的方法。在開發過程中,我們經常會遇到需要將嵌套結構從資料庫中解碼並映射到對應的資料傳輸物件(DTO)中的情況。 mongo'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 也應該要對應巢狀值嗎?

解決方法

json?但是 go mongodb 驅動程式可與 bson 配合使用

#結構體標籤用於定義 go 結構體欄位應如何對應到 mongodb 文件欄位。
course 結構中,您使用json 標籤,但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"

以上是使用 mongo'd db .Decode(&dto) 來映射巢狀結構的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Debian OpenSSL有哪些漏洞 Debian OpenSSL有哪些漏洞 Apr 02, 2025 am 07:30 AM

OpenSSL,作為廣泛應用於安全通信的開源庫,提供了加密算法、密鑰和證書管理等功能。然而,其歷史版本中存在一些已知安全漏洞,其中一些危害極大。本文將重點介紹Debian系統中OpenSSL的常見漏洞及應對措施。 DebianOpenSSL已知漏洞:OpenSSL曾出現過多個嚴重漏洞,例如:心臟出血漏洞(CVE-2014-0160):該漏洞影響OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻擊者可利用此漏洞未經授權讀取服務器上的敏感信息,包括加密密鑰等。

從前端轉型後端開發,學習Java還是Golang更有前景? 從前端轉型後端開發,學習Java還是Golang更有前景? Apr 02, 2025 am 09:12 AM

後端學習路徑:從前端轉型到後端的探索之旅作為一名從前端開發轉型的後端初學者,你已經有了nodejs的基礎,...

Beego ORM中如何指定模型關聯的數據庫? Beego ORM中如何指定模型關聯的數據庫? Apr 02, 2025 pm 03:54 PM

在BeegoORM框架下,如何指定模型關聯的數據庫?許多Beego項目需要同時操作多個數據庫。當使用Beego...

Go語言中用於浮點數運算的庫有哪些? Go語言中用於浮點數運算的庫有哪些? Apr 02, 2025 pm 02:06 PM

Go語言中用於浮點數運算的庫介紹在Go語言(也稱為Golang)中,進行浮點數的加減乘除運算時,如何確保精度是�...

Go的爬蟲Colly中Queue線程的問題是什麼? Go的爬蟲Colly中Queue線程的問題是什麼? Apr 02, 2025 pm 02:09 PM

Go爬蟲Colly中的Queue線程問題探討在使用Go語言的Colly爬蟲庫時,開發者常常會遇到關於線程和請求隊列的問題。 �...

GoLand中自定義結構體標籤不顯示怎麼辦? GoLand中自定義結構體標籤不顯示怎麼辦? Apr 02, 2025 pm 05:09 PM

GoLand中自定義結構體標籤不顯示怎麼辦?在使用GoLand進行Go語言開發時,很多開發者會遇到自定義結構體標籤在�...

在 Go 語言中,為什麼使用 Println 和 string() 函數打印字符串會出現不同的效果? 在 Go 語言中,為什麼使用 Println 和 string() 函數打印字符串會出現不同的效果? Apr 02, 2025 pm 02:03 PM

Go語言中字符串打印的區別:使用Println與string()函數的效果差異在Go...

在Go語言中使用Redis Stream實現消息隊列時,如何解決user_id類型轉換問題? 在Go語言中使用Redis Stream實現消息隊列時,如何解決user_id類型轉換問題? Apr 02, 2025 pm 04:54 PM

Go語言中使用RedisStream實現消息隊列時類型轉換問題在使用Go語言與Redis...

See all articles