Jimi
Jimi

Reputation: 1845

Changing the default MongoDB ObjectID generator

I'm using the mongo-go driver for Go to save some documents on mongoDb. Everyhting works fine, but i'm wondering if there is a way to change how the ID is auto-generated. Right now the document model in the code has the primitive.ObjectID type, is something like this

type Review struct {
    ID      primitive.ObjectID `json:"id,omitempty" bson:"_id,omitempty"`
    Title   string             `json:"title"`
    Text    string             `json:"text"`
    Rate    float64            `json:"rate"`
    Date    time.Time          `json:"date"`
    Product Product            `json:"product"`
}

And the document created is something like this

{
    "_id" : ObjectId("5d6f739a20d42db438016cb1"),
    "title" : "test-id",
    "text" : "rev-text",
    "rate" : 5.0,
    "date" : ISODate("2019-09-02T12:18:00.000+02:00"),
    "status" : "pending"
}

So far so good. However i want the ID to be a UUID, not an ObjectId. I know i can change the struct ID type to UUID or string and set that field when i'm saving the document, however i want to know if there is a way to change the default ObjectID generator of mongoDb so it generates a UUID automatically when saving a new document

Upvotes: 0

Views: 564

Answers (1)

Burak Serdar
Burak Serdar

Reputation: 51632

You don't have to use an ObjectID for _id:

  ID   string `json:"id,omitempty" bson:"_id,omitempty"`

Then you can insert any value you want for _id. However, you won't be able to auto-generate ID this way, you have to generate the ID yourself, and insert it with the generated ID.

Upvotes: 0

Related Questions