问题描述
我想查找在某个日期范围内创建的 MySql 表中的所有记录.
I want to find all records in a MySql table which was created within a certain range of date.
所以我写了:
import { Sequelize, Model, DataTypes, Op } from 'sequelize';
const sequelize = new Sequelize({
// some db connection config
dialect: 'mysql'
})
class Patient extends Model {
public guid!: number;
public name!: string;
public recordState: number = 0;
public createdAt?: Date;
public updatedAt?: Date
}
Patient.init({
guid: {
type: DataTypes.STRING,
primaryKey: true,
allowNull: false
},
name: { type: DataTypes.STRING, allowNull: false },
recordState: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0
},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE
}, {
sequelize,
modelName: 'Patient',
timestamps: false
})
Patient.findAll({
where: {
createdAt: {
[Op.between]: [new Date('2020-02-02'), new Date()]
}
}
})
但是,当我尝试用 tsc
编译它时,它会报告如下错误:
But, when I try to compile it with tsc
, it reports error like:
sequelize.ts:50:5 - error TS2322: Type '{ [between]: Date[]; }' is not assignable to type 'string | number | boolean | WhereAttributeHash | AndOperator | OrOperator | Literal | Where | Fn | Col | WhereOperators | Buffer | WhereGeometryOptions | (string | ... 2 more ... | Buffer)[]'.
Types of property '[Op.between]' are incompatible.
Type 'Date[]' is not assignable to type 'string | number | boolean | [number, number] | WhereAttributeHash | AndOperator | OrOperator | Literal | Where | ... 5 more ... | (string | ... 2 more ... | Buffer)[]'.
Type 'Date[]' is not assignable to type '(string | number | WhereAttributeHash | Buffer)[]'.
Type 'Date' is not assignable to type 'string | number | WhereAttributeHash | Buffer'.
Type 'Date' is not assignable to type 'WhereAttributeHash'.
Index signature is missing in type 'Date'.
50 createdAt: {
~~~~~~~~~
Found 1 error.
看来我不能在日期范围内使用 Op.between
?但是我用JS写类似的代码就ok了.
It seems I cannot use Op.between
with a date range? But it's ok when I wrote similar code in JS.
所以我想知道我的 TS 代码是否真的有问题,或者只是类型定义中缺少,或者不建议使用带有日期的 Op.between
?
So I wonder if there is really something wrong in my TS code or just a missing in the type definition, or maybe using Op.between
with dates is not recommended?
推荐答案
您传递的是日期对象而不是字符串.这样做:
You're passing a date object instead of a string. Do this:
Patient.findAll({
where: {
createdAt: {
[Op.between]: [new Date('2020-02-02').toISOString(), new Date().toISOString()]
}
}
})
这篇关于在 Sequelize with Dates 中使用 Op.between 时出现 TypeScript 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!