搜索
首页后端开发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行动:现实世界中的示例和应用程序Golang行动:现实世界中的示例和应用程序Apr 12, 2025 am 12:11 AM

Golang在实际应用中表现出色,以简洁、高效和并发性着称。 1)通过Goroutines和Channels实现并发编程,2)利用接口和多态编写灵活代码,3)使用net/http包简化网络编程,4)构建高效并发爬虫,5)通过工具和最佳实践进行调试和优化。

Golang:Go编程语言解释了Golang:Go编程语言解释了Apr 10, 2025 am 11:18 AM

Go语言的核心特性包括垃圾回收、静态链接和并发支持。1.Go语言的并发模型通过goroutine和channel实现高效并发编程。2.接口和多态性通过实现接口方法,使得不同类型可以统一处理。3.基本用法展示了函数定义和调用的高效性。4.高级用法中,切片提供了动态调整大小的强大功能。5.常见错误如竞态条件可以通过gotest-race检测并解决。6.性能优化通过sync.Pool重用对象,减少垃圾回收压力。

Golang的目的:建立高效且可扩展的系统Golang的目的:建立高效且可扩展的系统Apr 09, 2025 pm 05:17 PM

Go语言在构建高效且可扩展的系统中表现出色,其优势包括:1.高性能:编译成机器码,运行速度快;2.并发编程:通过goroutines和channels简化多任务处理;3.简洁性:语法简洁,降低学习和维护成本;4.跨平台:支持跨平台编译,方便部署。

SQL排序中ORDER BY语句结果为何有时看似随机?SQL排序中ORDER BY语句结果为何有时看似随机?Apr 02, 2025 pm 05:24 PM

关于SQL查询结果排序的疑惑学习SQL的过程中,常常会遇到一些令人困惑的问题。最近,笔者在阅读《MICK-SQL基础�...

技术栈收敛是否仅仅是技术栈选型的过程?技术栈收敛是否仅仅是技术栈选型的过程?Apr 02, 2025 pm 05:21 PM

技术栈收敛与技术选型的关系在软件开发中,技术栈的选择和管理是一个非常关键的问题。最近,有读者提出了...

如何在Go语言中使用反射对比并处理三个结构体的差异?如何在Go语言中使用反射对比并处理三个结构体的差异?Apr 02, 2025 pm 05:15 PM

Go语言中如何对比并处理三个结构体在Go语言编程中,有时需要对比两个结构体的差异,并将这些差异应用到第�...

在Go语言中如何查看全局安装的包?在Go语言中如何查看全局安装的包?Apr 02, 2025 pm 05:12 PM

在Go语言中如何查看全局安装的包?在使用Go语言开发过程中,经常会使用go...

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无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。