Additional 'id' field generated when publishing to MongoDB
I am learning the go and gin framework. I built a simple microservice that connects to a mongodb collection and everything works fine, but when I add a document using post it adds the "id" field instead of generating the key "_id" field, is there a way to avoid this?
This is my function:
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}}) }
This is my model:
type Post struct { ID primitive.ObjectID Title string `validate:"required,gte=2,lte=20"` Article string `validate:"required,gte=4,lte=40"` }
Correct answer
By default, the key for id
is id
. You should use the bson
tag to generate the key _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"` }
This is Documentation< /a>:
When marshaling a structure, each field will be lowercase to generate the key for the corresponding bson element. For example, a structure field named "foo" will generate the key "foo". This can be overridden via structure tags (e.g. bson:"foofield"
to generate the key "foofield").
When the document does not contain an element named _id
, the driver will automatically add an element (see Source code):
// 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) {
This is a demo:
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) } }
And the document created in the database:
demo> db.posts.find() [ { _id: ObjectId("64a53bcbb7be31ae42e6c00c"), title: 'test title', article: 'test content' } ]
The above is the detailed content of Additional 'id' field generated when publishing to MongoDB. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.
