1. User.beforeCreate(user => {
    2. if (user.accessLevel > 10 && user.username !== "Boss") {
    3. throw new Error("You can't grant this user an access level above 10!")
    4. }
    5. })

    This example will return an error:

    1. User.create({username: 'Boss', accessLevel: 20}).then(user => {
    2. console.log(user); // user object with username as Boss and accessLevel of 20
    3. });

    Sometimes you'll be editing more than one record at a time by utilizing the bulkCreate, update, destroy methods on the model. The following will emit whenever you're using one of those methods:

    WARNING: if you use individual hooks, all instances that are updated or destroyed will get loaded into memory before your hooks are called. The number of instances Sequelize can handle with individual hooks is limited by available memory.

    1. // Will select all records that are about to be deleted and emit before- + after- Destroy on each instance
    2. Model.update({username: 'Toni'}, { where: {accessLevel: 0}, individualHooks: true});
    3. // Will select all records that are about to be updated and emit before- + after- Update on each instance

    If you use Model.bulkCreate(…) with the updateOnDuplicate option, changes made in the hook to fields that aren't given in the updateOnDuplicate array will not be persisted to the database. However it is possible to change the updateOnDuplicate option inside the hook if this is what you want.

    1. // Bulk updating existing users with updateOnDuplicate option
    2. Users.bulkCreate([
    3. { id: 1, isMember: true },
    4. { id: 2, isMember: false }
    5. ], {
    6. updateOnDuplicate: ['isMember']
    7. User.beforeBulkCreate((users, options) => {
    8. for (const user of users) {
    9. if (user.isMember) {
    10. user.memberSince = new Date();
    11. }
    12. }
    13. // Add memberSince to updateOnDuplicate otherwise the memberSince date wont be
    14. // saved to the database
    15. });