Search code examples
node.jssequelize.jssequelize-cli

Can't use query function in migration


I'm trying to make a simple SELECT request in a migration file in JavaScript with Sequelize.

with this code:

const Sequelize = require("sequelize");
const { query, QueryTypes } = use_env_variable
  ? new Sequelize(process.env[use_env_variable], config)
  : new Sequelize(database, username, password, config);

module.exports = {
  up: async ({ addColumn, removeColumn }, { INTEGER }) => (
    const results = await query("SELECT * FROM table;", { type: QueryTypes.SELECT });
  ),
  down: async () => {}
});

I'm getting stuck with the error:

ERROR: Cannot read property 'options' of undefined

meanwhile, if i don't specifically import only query and QueryTypes from sequelize and use the conventionnal sequelize.query or sequelize.QueryTypes.SELECT it will works:

const Sequelize = require("sequelize");
const sequelize = use_env_variable
  ? new Sequelize(process.env[use_env_variable], config)
  : new Sequelize(database, username, password, config);

module.exports = {
  up: async ({ addColumn, removeColumn }, { INTEGER }) => (
    const results = await sequelize.query("SELECT * FROM table;", { type: sequelize.QueryTypes.SELECT });
  ),
  down: async () => {}
});

the code above works fine in the way I need, but why ? If I mix both code in order to have sequelize.query and query like importing like that:

const Sequelize = require("sequelize");
const sequelize = use_env_variable
  ? new Sequelize(process.env[use_env_variable], config)
  : new Sequelize(database, username, password, config);
const { query, QueryTypes } = use_env_variable
  ? new Sequelize(process.env[use_env_variable], config)
  : new Sequelize(database, username, password, config);

I figured myself that console.log(query === sequelize.query); would return true but using query instead of sequelize.query will provoke the ERROR: Cannot read property 'options' of undefined error...

where did i do something wrong ?


Solution

  • Someone from the sequelize' Slack answered me:

    It's normal. query is a method that needs to know the instance it's being called on. If you extract it from the sequelize instance, its this will be undefined instead of the sequelize instance you can do this though:

    const sequelize = new Sequelize(process.env[config.use_env_variable], config);
    const { QueryTypes } = sequelize;
    const query = sequelize.query.bind(sequelize);