Passing options to Sequelize hook not working

Viewed 1025

I am currently trying to pass options to a Sequelize hook, but when I try to access the passed options within the hook, they are always undefined. Anyone got an idea what I am overseeing?

Here's the query:

db.customer.findAll({
            where: searchObject,
            offset: offset,
            limit: limit,
            order: orderOptions
        }, {
            user: req.user
        }).then(customers => {
// more code here

And here's the model including the hook definition:

const db = require("../server/database");
const Sequelize = require('sequelize');
const Op = Sequelize.Op;

module.exports = function (sequelize, Sequelize) {

  var Customer = sequelize.define('customer', {
    id: {
      autoIncrement: true,
      primaryKey: true,
      allowNull: false,
      type: Sequelize.INTEGER
    },
    salutation: {
      type: Sequelize.TEXT
    },
    title: {
      type: Sequelize.TEXT
    },
    firstName: {
      type: Sequelize.TEXT
    },
    lastName: {
      type: Sequelize.TEXT
    }
  }, {
    freezeTableName: true
  });

  Customer.beforeFindAfterExpandIncludeAll((instance, options) => {
    console.log(options);
  });

  return Customer;
}
1 Answers

I found the solution to the problem myself. I dropped the options part completely and went with the following approach which works just as intended:

db.customer.findAll({
            where: searchObject,
            offset: offset,
            limit: limit,
            order: orderOptions,
            user: req.user
        }).then(customers => {
// more code here
Customer.beforeFindAfterExpandIncludeAll((instance) => {
    console.log(instance.user); // This logs the user object correctly
  });

The initial approach was demonstrated in several other StackOverflow posts, but does not appear to be working anymore.

While the approach shown in this post might make it a bit harder to understand the purpose of the user object being passed, it gets the job done just fine.

Related