我正在尝试创建一个带有 USER 类的 API,该类可以有不止一种方法来使用 API 进行身份验证。
我设法让它与只有 1 个凭据的 1 个用户一起使用,但是当尝试扩展以允许多个凭据时,我得到了错误:UnhandledPromiseRejectionWarning: SequelizeDatabaseError: (conn=498, no: 1265, SQLState: 01000) Data truncated for column 'type' at row 1
我目前拥有的是:
User.hasMany(Credential, { foreignKey: 'id', sourceKey: 'id' });
和这个:
//Credential.ts
export function CredentialInit(sequelize: Sequelize) {
let cred = Object.keys(CredentialType);
let credArr: string[] = [];
for(let i = 0; i < cred.length/2; i++) {
credArr.push(`${i}`);
};
Credential.init({
email: {
type: DataTypes.STRING,
allowNull: true
},
password: {
type: DataTypes.STRING,
allowNull: true
},
token: {
type: DataTypes.STRING,
allowNull: true
},
type: {
type: DataTypes.ENUM,
values: credArr,
allowNull: false
}
}, {
sequelize: sequelize,
tableName: 'credentials'
});
}
export enum CredentialType {
EMAIL,
TOKEN
}
export class Credential extends BaseModel {
public type!: CredentialType;
public token?: string;
public email?: string;
public password?: string;
}
也有这个模型从我所有的其他模型中删除这些东西。
//BaseModel.ts
export class BaseModel extends Model {
public id?: number;
public readonly createdAt?: Date;
public readonly updatedAt?: Date;
}
知道为什么我收到这条消息吗?
我这样写是因为我不想两次声明枚举的内容..如果改变了,我希望它在任何地方都改变......
最佳答案
好吧,经过更多的实验,我找到了一种方法。
由于枚举选项在 typescript/javascript 中表示为数字,因此我更改了与枚举对应的数据库类型:
Credential.init({
email: {
type: DataTypes.STRING,
allowNull: true
},
password: {
type: DataTypes.STRING,
allowNull: true
},
token: {
type: DataTypes.STRING,
allowNull: true
},
type: {
type: DataTypes.INTEGER,
allowNull: false
}
}, {
sequelize: sequelize,
tableName: 'credentials'
});
当它作为整数保存到数据库时,错误就消失了。
关于node.js - 将 ENUM 与 Sequelize 和 Typescript 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59506149/