搜尋
首頁後端開發Golang發佈到 MongoDB 時產生的附加「id」字段

发布到 MongoDB 时生成的附加“id”字段

問題內容

我正在學習go和gin框架。 我建立了一個連接到 mongodb 集合的簡單微服務,一切正常,但是當我使用 post 添加文件時,它添加“id”字段而不是生成關鍵“_id”字段,有沒有辦法避免這種情況?

這是我的功能:

func (r *rest) createpost(c *gin.context) {
var postcollection = database.getcollection(r.db, "godb")
ctx, cancel := context.withtimeout(context.background(), 10*time.second)
post := new(model.post)
defer cancel()

if err := c.shouldbindjson(&post); err != nil {
    c.json(http.statusbadrequest, gin.h{"message": err})
    log.fatal(err)
    return
}

// validation
if err := post.validate(); err == nil {
    c.json(http.statusok, gin.h{"input": "valid"})
} else {
    c.json(http.statusbadrequest, gin.h{"input validation": err.error()})
    return
}

postpayload := model.post{
    id:      primitive.newobjectid(),
    title:   post.title,
    article: post.article,
}

result, err := postcollection.insertone(ctx, postpayload)

if err != nil {
    c.json(http.statusinternalservererror, gin.h{"message": err})
    return
}

c.json(http.statusok, gin.h{"message": "posted succesfully", "data": 
map[string]interface{}{"data": result}})
}

這是我的模型:

type Post struct {
ID      primitive.ObjectID
Title   string `validate:"required,gte=2,lte=20"`
Article string `validate:"required,gte=4,lte=40"`
}

正確答案


預設情況下,id 的金鑰是 id。您應該使用 bson 標籤來產生金鑰 _id

type post struct {
    id      primitive.objectid `bson:"_id"`
    title   string             `validate:"required,gte=2,lte=20"`
    article string             `validate:"required,gte=4,lte=40"`
}

這是文件:

編組結構時,每個欄位都會小寫以產生對應 bson 元素的金鑰。例如,名為“foo”的結構體欄位將產生鍵“foo”。這可以透過結構標記覆蓋(例如 bson:"foofield" 來產生鍵“foofield”)。

當文件不包含名為 _id 的元素時,驅動程式會自動新增一個元素(請參閱原始碼):

// ensureid inserts the given objectid as an element named "_id" at the
// beginning of the given bson document if there is not an "_id" already. if
// there is already an element named "_id", the document is not modified. it
// returns the resulting document and the decoded go value of the "_id" element.
func ensureid(
    doc bsoncore.document,
    oid primitive.objectid,
    bsonopts *options.bsonoptions,
    reg *bsoncodec.registry,
) (bsoncore.document, interface{}, error) {

這是一個示範:

package main

import (
    "context"

    "go.mongodb.org/mongo-driver/bson/primitive"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type post struct {
    id      primitive.objectid `bson:"_id"`
    title   string             `validate:"required,gte=2,lte=20"`
    article string             `validate:"required,gte=4,lte=40"`
}

func main() {
    client, err := mongo.connect(context.background(), options.client().applyuri("mongodb://localhost"))
    if err != nil {
        panic(err)
    }

    postcollection := client.database("demo").collection("posts")
    post := post{
        id:      primitive.newobjectid(),
        title:   "test title",
        article: "test content",
    }
    if err != nil {
        panic(err)
    }

    if _, err = postcollection.insertone(context.background(), post); err != nil {
        panic(err)
    }
}

以及在資料庫中建立的文件:

demo> db.posts.find()
[
  {
    _id: ObjectId("64a53bcbb7be31ae42e6c00c"),
    title: 'test title',
    article: 'test content'
  }
]

以上是發佈到 MongoDB 時產生的附加「id」字段的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
在Golang和Python之間進行選擇:適合您的項目在Golang和Python之間進行選擇:適合您的項目Apr 19, 2025 am 12:21 AM

golangisidealforperformance-Critical-clitageAppations and ConcurrentPrompromming,而毛皮刺激性,快速播種和可及性。 1)forhigh-porformanceneeds,pelectgolangduetoitsefefsefefseffifeficefsefeflicefsiveficefsiveandconcurrencyfeatures.2)fordataa-fordataa-fordata-fordata-driventriventriventriventriventrivendissp pynonnononesp

Golang:並發和行動績效Golang:並發和行動績效Apr 19, 2025 am 12:20 AM

Golang通過goroutine和channel實現高效並發:1.goroutine是輕量級線程,使用go關鍵字啟動;2.channel用於goroutine間安全通信,避免競態條件;3.使用示例展示了基本和高級用法;4.常見錯誤包括死鎖和數據競爭,可用gorun-race檢測;5.性能優化建議減少channel使用,合理設置goroutine數量,使用sync.Pool管理內存。

Golang vs. Python:您應該學到哪種語言?Golang vs. Python:您應該學到哪種語言?Apr 19, 2025 am 12:20 AM

Golang更適合系統編程和高並發應用,Python更適合數據科學和快速開發。 1)Golang由Google開發,靜態類型,強調簡潔性和高效性,適合高並發場景。 2)Python由GuidovanRossum創造,動態類型,語法簡潔,應用廣泛,適合初學者和數據處理。

Golang vs. Python:性能和可伸縮性Golang vs. Python:性能和可伸縮性Apr 19, 2025 am 12:18 AM

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

Golang vs.其他語言:比較Golang vs.其他語言:比較Apr 19, 2025 am 12:11 AM

Go語言在並發編程、性能、學習曲線等方面有獨特優勢:1.並發編程通過goroutine和channel實現,輕量高效。 2.編譯速度快,運行性能接近C語言。 3.語法簡潔,學習曲線平緩,生態系統豐富。

Golang和Python:了解差異Golang和Python:了解差異Apr 18, 2025 am 12:21 AM

Golang和Python的主要區別在於並發模型、類型系統、性能和執行速度。 1.Golang使用CSP模型,適用於高並發任務;Python依賴多線程和GIL,適合I/O密集型任務。 2.Golang是靜態類型,Python是動態類型。 3.Golang編譯型語言執行速度快,Python解釋型語言開發速度快。

Golang vs.C:評估速度差Golang vs.C:評估速度差Apr 18, 2025 am 12:20 AM

Golang通常比C 慢,但Golang在並發編程和開發效率上更具優勢:1)Golang的垃圾回收和並發模型使其在高並發場景下表現出色;2)C 通過手動內存管理和硬件優化獲得更高性能,但開發複雜度較高。

Golang:雲計算和DevOps的關鍵語言Golang:雲計算和DevOps的關鍵語言Apr 18, 2025 am 12:18 AM

Golang在雲計算和DevOps中的應用廣泛,其優勢在於簡單性、高效性和並發編程能力。 1)在雲計算中,Golang通過goroutine和channel機制高效處理並發請求。 2)在DevOps中,Golang的快速編譯和跨平台特性使其成為自動化工具的首選。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

記事本++7.3.1

記事本++7.3.1

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

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具