Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize - called with something that's not a subclass of Sequelize.Model

I'm working on app but I having this issue using Node.js and Sequelize for Postgresql :

      throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not a subclass of Sequelize.Model');
      ^

Error: Expense.class BelongsTo extends Association {
  constructor(source, target, options) {
    super(source, target, options);

    <....LOT OF CODE FROM SEQUELIZE ....>

    if ((fieldsOrOptions || {}).transaction instanceof Transaction) {
      options.transaction = fieldsOrOptions.transaction;
    }
    options.logging = (fieldsOrOptions || {}).logging;

    return association.target.create(values, fieldsOrOptions).then(newAssociatedObject =>
      sourceInstance[association.accessors.set](newAssociatedObject, options)
    );
  }
} called with something that's not a subclass of Sequelize.Model

I don't understand this error, especially the last line "called with something that's not a subclass of Sequelize.Model". Here is the models :

User model

const models = require('./index');
const Expense = models.User;

module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define('User', {
    firstname: DataTypes.STRING,
    lastname: DataTypes.STRING,
    email: DataTypes.STRING,
    password: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        User.hasMany(models.Expense);
      }
    }
  });
  console.log(models);

  User.hasMany(Expense, {as: 'Expenses', foreignKey: 'userId'});

  return User;
};

And Expense model

const models = require('./index');
const User = models.User;

module.exports = (sequelize, DataTypes) => {
  var Expense = sequelize.define('Expense', {
    name: DataTypes.STRING,
    amount: DataTypes.INTEGER,
    date: DataTypes.INTEGER
  }, {
    classMethods: {
    }
  });

  Expense.belongsTo(User, { foreignKey: 'userId' });

  return Expense;
};

And the controller for creating an expense :

createExpense: function(req, res) {
    const user = User.findOne({ where: { id: req.params.id } });
    Expense.create({
        name: req.body.name,
        amount: req.body.amount,
        date: req.body.date,
        User: user
    },{
       include: [
           {
               model: User
           }
       ]
    }).then((created) => {
        res.status(200).send({ success: true, message: 'Dépense ajoutée !' });
    });
}

Does someone have already see an error that look like that ? I search for few days without any issue, if someone could help I'll really appreciate,

thank !

like image 236
Antonin Mrchd Avatar asked Nov 07 '17 22:11

Antonin Mrchd


1 Answers

I have a same problem before, but I found a reason. Key point is that your models must under a same sequelize class.

You can look my project mini-shop on github.

like image 147
vonfly Avatar answered Nov 02 '22 02:11

vonfly