我遇到一个问题,当我从数据库查询数据时,它会为我的记录生成一个随机 UUID,而不是使用正确的 UUID。
假设我有下表
import {
Column,
DataType,
Default,
Model,
PrimaryKey,
Table,
IsLowercase,
Unique
} from 'sequelize-typescript'
@Table({ underscored: true, paranoid: true, timestamps: true })
export abstract class BaseModel<T> extends Model<T> {
@PrimaryKey
@Default(DataType.UUIDV4)
@Column(DataType.UUID)
id: string
@Column
readonly createdAt: Date
@Column
readonly updatedAt: Date
@Column
readonly deletedAt: Date
constructor(input?: any) {
super()
if (input) {
Object.assign(this, input)
}
}
}
@Table
export default class Foo extends BaseModel<Tag> {
@Unique
@IsLowercase
@Column(DataType.STRING(32))
name: string
toJSON(): object {
return {
id: this.id,
name: this.name,
updatedAt: this.updatedAt,
}
}
}
然后创建一个并找到一个对象返回
const f = await Foo.findAll();
console.log("created id", f.id);
// => created id cda0f763-2384-4116-970d-f6418678787c
const foundFoo= await Foo.findOne();
console.log("found id", foundFoo.id);
// => found id 6ae277c7-1797-4bfa-a9dd-c893d004a151
我现在 ID 已被存储,甚至被正确请求,因为如果我这样做
const f = await Foo.findAll();
console.log("created id", f.id);
// => created id cda0f763-2384-4116-970d-f6418678787c
const foundFoo= await Foo.findOne({ raw: true });
console.log("found id", foundFoo.id);
// => found id cda0f763-2384-4116-970d-f6418678787c
但现在我有一个普通对象,没有任何我需要的 Sequelize 方法。为什么会出现这种情况?
我在 Linux 上运行 node.js v18.18.2、sequelize ^6.37.1、sequelize-typescript: ^2.1.3
我认为这是您的
id
字段阴影续集的 getter 和 setter 的情况,应该将其删除。使用您的示例模型,您应该这样创建它:
@Table({ underscored: true, paranoid: true, timestamps: true })
export abstract class BaseModel<T> extends Model<T> {
/* I have removed the id field. */
@Column
readonly createdAt: Date
@Column
readonly updatedAt: Date
@Column
readonly deletedAt: Date
constructor(input?: any) {
super()
if (input) {
Object.assign(this, input)
}
}
}
@Table
export default class Foo extends BaseModel<Tag> {
@Unique
@IsLowercase
@Column(DataType.STRING(32))
name: string
toJSON(): object {
return {
id: this.id,
name: this.name,
updatedAt: this.updatedAt,
}
}
}
Foo.init(
{
id: {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4 // Or DataTypes.UUIDV1
},
},
{ sequelize },
);