Sequelize - 用不是Sequelize.Model子类的东西调用

时间:2017-11-07 22:26:44

标签: node.js sequelize.js

我正在开发应用程序,但是我在使用Node.js和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

我不明白这个错误,尤其是最后一行“使用不是Sequelize.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;
};

费用模型

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;
};

用于创建费用的控制器

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 !' });
    });
}

是否有人看到过这样的错误?我搜索了几天没有任何问题,如果有人可以帮助我会非常感激,

谢谢!

2 个答案:

答案 0 :(得分:0)

我之前也遇到过同样的问题,但是找到了原因。关键是您的模型必须在相同的sequelize类下。

您可以在github上查看我的项目mini-shop

答案 1 :(得分:0)

尽管迟到了3年...我认为,这是由于进口不良造成的。在“用户模型”中的“费用模型”中的导入使用此行,看起来有点腥:

const Expense = models.User;

但是从相当普遍的角度来看,这种错误消息可能是在诸如User.hasMany(Expense, {as: 'Expenses', foreignKey: 'userId'});这样的行中创建关联时提示错误的提示

这里是another answer,涉及一个类似的问题。例如,在我的情况下,错误是由于未使用定义名称访问我的模型而引起的(<-取决于您的设置!)