javascriptnode.jsrestexpresssequelize.js

Node.js - SequelizeDatabaseError: column "user_id" does not exist


I have a very simple schema but when I try to make a call for a data it returns me the error

SequelizeDatabaseError: column "user_id" does not exist

My database consists of three tables only. Below is the schema file for all of them:

Users

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('users', {
    email: DataTypes.STRING,
    password: DataTypes.STRING
  }, {});
  User.associate = function (models) {
    User.hasMany(models.survey_instances)
  };
  return User;
};

Survey instances


module.exports = (sequelize, DataTypes) => {
  const SurveyInstances = sequelize.define('survey_instances', {
    userId: {
      field: 'user_id',
      type: DataTypes.INTEGER
    },
    templateId: {
      field: 'template_id',
      type: DataTypes.INTEGER
    },
    fields: DataTypes.JSONB,
  }, {
    underscored: true,
  });
  SurveyInstances.associate = function (models) {
    SurveyInstances.belongsTo(models.survey_templates, { foreignKey: 'templateId' })
    SurveyInstances.belongsTo(models.users, { foreignKey: 'userId' })
  };
  return SurveyInstances;
};

Survey Templates

module.exports = (sequelize, DataTypes) => {
  const SurveyTemplates = sequelize.define('survey_templates', {
    fields: DataTypes.JSONB,
  }, {});
  SurveyTemplates.associate = function (models) {
    SurveyTemplates.hasMany(models.survey_instances)
  };
  return SurveyTemplates;
};

My database is populated and I make the call by:

http://localhost:3000/templates?id=1

The code handling this endpoint in node is:

app.get('/templates', authenticateToken, async (req, res) => {
  const templates = await db.survey_instances.findByPk(1);
  res.send(templates);
});

I'm new to node so maybe the error is obvious but I cant see it. I would really appreciate it if someone helped me out. Thank you!


Solution

  • I figured out the issue. There is a bug in the new Sequelize updates that don't make the underscored: true option work. More details can be found here.

    So I am now just using camel case instead of snake case. Everthing's working now.