A Note About Transactions

Note that many model operations in Sequelize allow you to specify a transaction in the options parameter of the method. If a transaction is specified in the original call, it will be present in the options parameter passed to the hook function. For example, consider the following snippet:

  1. // Here we use the promise-style of async hooks rather than
  2. // the callback.
  3. User.addHook('afterCreate', (user, options) => {
  4. // 'transaction' will be available in options.transaction
  5. // This operation will be part of the same transaction as the
  6. // original User.create call.
  7. return User.update({
  8. mood: 'sad'
  9. }, {
  10. where: {
  11. id: user.id
  12. },
  13. transaction: options.transaction
  14. });
  15. });
  16. sequelize.transaction(transaction => {
  17. User.create({
  18. username: 'someguy',
  19. mood: 'happy',
  20. transaction
  21. });
  22. });

If we had not included the transaction option in our call to User.update in the preceding code, no change would have occurred, since our newly created user does not exist in the database until the pending transaction has been committed.

Internal Transactions

It is very important to recognize that sequelize may make use of transactions internally for certain operations such as Model.findOrCreate. If your hook functions execute read or write operations that rely on the object's presence in the database, or modify the object's stored values like the example in the preceding section, you should always specify { transaction: options.transaction }.

If the hook has been called in the process of a transacted operation, this makes sure that your dependent read/write is a part of that same transaction. If the hook is not transacted, you have simply specified { transaction: null } and can expect the default behaviour.