search

Home  >  Q&A  >  body text

Ensure the uniqueness of the incremental value of Sequelize

I currently use Sequelize's increment() function to increment the column of order number values. For example: .increment("order_no", { by: 1 });

Occasionally a request will arrive at my API simultaneously within the same second, resulting in duplicate order number values.

Is there a way to ensure that the incremental value of the order number is unique? Do I need to wrap increment in transaction? After creating an order number, should I randomly and regularly check if there are duplicates? Not sure the correct way to solve this problem.

According to Sequelize’s documentation (https://sequelize.org/docs/v6/core-concepts/model-instances/#incrementing-and-decrementing-integer-values)

In order to avoid concurrency problems, Sequelize provides increment and decrement instance methods to increment/decrement the value of the instance.

However, although it appears that this method works, you will still get duplicate values ​​when used.

P粉616111038P粉616111038452 days ago475

reply all(1)I'll reply

  • P粉793532469

    P粉7935324692023-09-07 11:34:14

    I think if there is a duplicate order ID, you can try to catch the error and retry the operation, generating a new order ID.

    reply
    0
  • Cancelreply