Skip to content

Instantly share code, notes, and snippets.

@kneerunjun
Last active January 9, 2023 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kneerunjun/68df45b8600fb08768eff4fc95be4beb to your computer and use it in GitHub Desktop.
Save kneerunjun/68df45b8600fb08768eff4fc95be4beb to your computer and use it in GitHub Desktop.
This demonstrates typical pitfalls when you make a datamodel in Go and expect it work smoothly with mgo or mongo-driver, but it does not.
package data
import(
"gopkg.in/mgo.v2/bson"
)
type User struct {
ID bson.ObjectId `bson:"_id"`
Name string `bson:"name"`
Email string `bson:"email"`
}
// for seeding purposes, testing environmen
func seed_data(){
users := []User{
User{Name:"JohnDoe", Email:"jdoe@somedomain.com"},
User{Name:"ParryJean", Email:"parryJ@somedomain.com"},
}
// get your connection up here
var coll *mgo.Collection
for _, u := range users {
err :=coll.Insert(u)
if err !=nil{
fmt.Errorf("Error inserting user into the database")
}
}
}

The above code snippet is actually vanilla and for a cursory look everything seems to be fine. Only when you run the code you realise the error is related to the USer.Id field for being empty. You, just like me when I did this for the first time were expecting the mgo framework to generate the ID if empty. For that to happen you are missing a minute detail

type User struct {
  ID bson.ObjectId `bson:"_id, omitempty"`
  Name string `bson:"name"`
  Email string `bson:"email"`
}

Without specifying omitempty you are essentially indicating to mgo that you would be generating the objectId before insertion. Hence mgo steps aside to handover control. When you dont supply the ID (that you were committing to) Mongo throws back. Contrast to that when omitempty mgo understands its empty and you no longer intend to supply a new ID. Mgo then auto generats the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment