I would like to use UUID as my _id attribute:
func (mongoDB *MongoDB) CreateBook(ctx context.Context, book *ds.Book) (err error) {
book.ID = uuid.New().String()
collection := mongoDB.Database.Collection(BookCollection)
insertResult, err := collection.InsertOne(context.TODO(), book)
if err != nil {
return
}
uuid := insertResult.InsertedID.(string)
task.ID = uuid
return
}
I'm wondering if I need to check if the UUID generated is not unique? like the code below:
func (mongoDB *MongoDB) CreateBook(ctx context.Context, book *ds.Book) (error) {
for ;; {
book.ID = uuid.New().String()
collection := mongoDB.Database.Collection(BookCollection)
insertResult, err := collection.InsertOne(context.TODO(), book)
if err == nil {
uuid := insertResult.InsertedID.(string)
book.ID = uuid
return err
}
}
}
The problem with this code is I don't know how to make sure that the error returned is duplicate Primary Key error since the error returned is generic error object. So the question is, it is necessary to check if the UUID generated is unique and if its necessary, how do I make sure that the error returned by InsertOne is duplicate PK error?