首页 > 后端开发 > Golang > 正文

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

王林
发布: 2024-02-05 23:21:07
转载
841人浏览过

发布到 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”)。

腾讯混元文生视频
腾讯混元文生视频

腾讯发布的AI视频生成大模型技术

腾讯混元文生视频 137
查看详情 腾讯混元文生视频

当文档不包含名为 _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中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号