-1

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?

nanakondor
  • 615
  • 11
  • 25
  • Currently there's no easy way to tell if the error is due to duplicate key. See possible duplicate: [With mongo-go-driver, how do I efficiently retrieve duplicated field name from WriteError?](https://stackoverflow.com/questions/62711694/with-mongo-go-driver-how-do-i-efficiently-retrieve-duplicated-field-name-from-w/62712309#62712309) – icza Oct 30 '20 at 12:04
  • I'm hesitant to discourage defensive programming, but I would point out that the purpose of UUID is to allow independent generation of primary keys with a probability of collisions bordering on the impossible. ["For example, the number of random version-4 UUIDs which need to be generated in order to have a 50% probability of at least one collision is 2.71 quintillion"](https://en.wikipedia.org/wiki/Universally_unique_identifier) – Adrian Oct 30 '20 at 13:32

1 Answers1

0

The server will enforce the uniqueness of _id values in a collection. If you try to insert two documents with the same _id, the second insert will fail. Thus you should certainly do what you can to generate unique _id values, but you do not have to guarantee uniqueness as the server will do that.

D. SM
  • 13,584
  • 3
  • 12
  • 21