How to autogenerate id when I have defined id uint64 `bson:"_id"`

Viewed 114

Let's say you have a simple struct

type User struct {
    ID              uint64    `json:"id" bson:"_id"`
    UserName        string    `json:"user_name" bson:"userName"`
    Email           string    `json:"email" bson:"email"`
}

u := User{
    userName: "me",
    Email:    "me@mail.com"
}

I am trying to insert this object in MongoDB collection like so:

r, err := collection.InsertOne(context.TODO(), u)

The ID field here has a value of 0 because I didn't specify a value. The problem is that MongoDB does not auto-generate the _id field but instead, sets the value to equal 0, which is very logical but not the outcome I would like.

Is there a way to auto-generate the _id with this method?

1 Answers

You should use the omitempty tag on ID.

type User struct {
    ID              primitive.ObjectID    `json:"id" bson:"_id,omitempty"`
    UserName        string    `json:"user_name" bson:"userName"`
    Email           string    `json:"email" bson:"email"`
}

If you don't specify the omitepmty tag, then the behaviour is as specified on Go structs; whereby if any of struct fields are omitted it will be zero-valued.

In this case because you have specified the field type to be primitive.ObjectID, ObjectId('000000000000000000000000') is the zero value.

Hence you need to generate an ID when you create the struct:

collection.InsertOne(context.TODO(), 
                     User{ ID: primitive.NewObjectID(), 
                           UserName: "me", 
                           Email: "me@mail.com"})
Related