gpt4 book ai didi

node.js - 类型错误 : Cannot read property 'length' of undefined at model create

转载 作者:行者123 更新时间:2023-12-03 22:36:55 25 4
gpt4 key购买 nike

我正在创建一个模型和一个 Controller 来执行一些金融交易,如借方和贷方。

当我尝试使用 <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)

Controller 源代码是:
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 中的所有值插入。

有谁可以帮助我吗?

提前致谢,

最佳答案

看起来您忘记在 src/database/index.js 中导入用户模型。

关于node.js - 类型错误 : Cannot read property 'length' of undefined at model create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58262382/

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