gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:21:05 24 4
gpt4 key购买 nike

我正在开发应用程序,但我在使用 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;
};

以及创建费用的 Controller :

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

是否有人已经看到类似的错误?我搜索了几天没有任何问题,如果有人可以提供帮助,我将不胜感激,

谢谢!

最佳答案

我之前也遇到过同样的问题,后来找到原因了。关键是你的模型必须在同一个 sequelize 类下。

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

关于node.js - Sequelize - 使用不是 Sequelize.Model 子类的东西调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47168451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com