javascript - Sequelize Not Null 错误,即使传递的对象不是 null
问题描述
目前从我的 notnull 验证器收到错误,但是我通过一个明显具有值的新对象传递定义的变量。用户、站点和联系人都是关联的,所以我不确定是否在我的 api 路由中,如果我不创建属性,那么只需从我的发布请求中传递它们,但是因为这是 MySql,我相信它是必需的,我可以肯定是错的。任何帮助或见解将不胜感激。
Api 路线
console.log(req.body);
db.Case.create({
caseName: req.body.caseName,
userId: req.body.userId,
siteId: req.body.siteId,
contactId: req.body.contactId
}).then((response) => {
console.log(response);
res.json(response)
}).catch((err) => {
console.log(err);
})
})
模型
module.exports = (sequelize, DataTypes) => {
const Case = sequelize.define('Case', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
caseName: {
type: DataTypes.STRING,
allowNull: false,
},
createdAt: {
type: DataTypes.DATE
},
updatedAt: {
type: DataTypes.DATE,
},
})
Case.associate = (models) => {
Case.belongsTo(models.User, {
foreignKey : {
allowNull : false
}
})
Case.belongsTo(models.Site, {
foreignKey: {
allowNull: false
}
})
Case.belongsTo(models.Contact, {
foreignKey: {
allowNull : false
}
})
}
return Case;
}
发布请求
const caseName = $('#caseName');
const UserId = sessionStorage.getItem('id');
const SiteId = $('#insertSite').attr('id');
const ContactId = $('#insertContact').attr('id');
if(!caseName.val().trim() || !UserId || !SiteId || !ContactId){
console.log('Please enter all of the Case information')
return;
}
const newCase = {
caseName: caseName.val().trim(),
UserId: UserId,
SiteId: SiteId,
ContactId: ContactId,
};
console.log(newCase);
axios.post('/api/Case', newCase).then((res) => {
console.log('New Case has been added' + res);
}).catch((err) => {
console.log(err);
});
正在通过的测试对象
{
caseName: 'tttttttttt',
UserId: '1',
SiteId: 'insertSite',
ContactId: 'insertContact'
}
错误响应
errors: [
ValidationErrorItem {
message: 'Case.UserId cannot be null',
type: 'notNull Violation',
path: 'UserId',
value: null,
origin: 'CORE',
instance: [Case],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
},
ValidationErrorItem {
message: 'Case.SiteId cannot be null',
type: 'notNull Violation',
path: 'SiteId',
value: null,
origin: 'CORE',
instance: [Case],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
},
ValidationErrorItem {
message: 'Case.ContactId cannot be null',
type: 'notNull Violation',
path: 'ContactId',
value: null,
origin: 'CORE',
instance: [Case],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
}
]
}
解决方案
您的 API 创建方法中的属性未正确大写。
caseName: req.body.caseName,
userId: req.body.userId,
siteId: req.body.siteId,
contactId: req.body.contactId
: 对于 3 个外键的两边都需要固定大小写。
推荐阅读
- javascript - 如何使用 excel.js 库编辑 Multer 发布的文件?
- c++ - 链表插入,指针混淆
- python - 使用 OpenCV 检测文档扫描中的矩形签名字段
- mysql - 如何将 sql join 查询转换为 sequelizejs 查询
- node.js - SPFX 站点(SharePoint 2016 本地站点与反应)不断重新加载。该怎么办?
- docker - 使用 ENV 参数设置容器 PATH
- django - 如何在django中借助Forign Key访问其他模型的所有字段
- spring - 如何使用 Spring Pageable 在自定义查询 JPQL 上对多个字段执行排序
- android - Flutter:显示 PDF 封面图片
- selenium - 如何参考第一列中的名称启用第二列中的复选框?