我正在创建一个模型和一个控制器来执行一些金融交易,例如借方和贷方。
当我尝试使用<model>.create
方法“创建”时,它返回以下错误:
(node:5192) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
at Transaction._initValues (/Users/username/Documents/Projetos/projectname/node_modules/sequelize/lib/model.js:140:49)
控制器源代码为:
import * as Yup from 'yup';
import Transaction from '../models/Transaction';
class TransactionController {
async store(req, res) {
const schema = Yup.object().shape({
id_user: Yup.number().required(),
id_category: Yup.number().required(),
id_wallet: Yup.number(),
title: Yup.string()
.min(6)
.max(32)
.required(),
description: Yup.string(),
amount: Yup.number()
.round('floor')
.moreThan(0)
.positive()
.required(),
is_credit: Yup.bool()
.required()
.default(true),
});
if (!(await schema.isValid(req.body))) {
return res.status(400).json({
error:
'Validation failed, see documentation for insert new transaction',
});
}
const {
id_user,
id_category,
id_wallet,
title,
description,
amount,
is_credit,
} = await Transaction.create(req.body).catch(error => {
console.log('error', error);
});
return res.json({
id_user,
id_category,
id_wallet,
title,
description,
amount,
is_credit,
});
}
}
export default new TransactionController();
模型库为:
class Transaction extends Model {
static init(sequelize) {
super.init(
{
id_user: Sequelize.INTEGER,
id_category: Sequelize.INTEGER,
id_wallet: Sequelize.INTEGER,
title: Sequelize.STRING,
description: Sequelize.STRING,
amount: Sequelize.DECIMAL(10, 2),
is_credit: Sequelize.BOOLEAN,
},
{
sequelize,
}
);
return this;
}
/* static associate(models) {
this.belongsTo(models.File, { foreignKey: 'avatar_id', as: 'avatar' });
} */
static associate(models) {
this.belongsTo(models.User, { foreignKey: 'id_user', as: 'id' });
}
}
export default Transaction;
我无法理解length
的含义,因为我正在用YUP验证正文,并尝试使用JSON BODY中的所有值进行插入。
有人可以帮我吗?
预先感谢
答案 0 :(得分:0)
好像您忘记了在src / database / index.js中导入用户模型。
答案 1 :(得分:0)
在调用请求之前,必须先执行database.js类。例如:
如果您使用文件导入路由,则必须在执行控制器之前导入database.js并执行。