Sequelize Date Range Error When Using Op.between with TypeScript

My goal is to retrieve all records from a MySql table that were created within a specific date range.

To accomplish this, I created the following code snippet:

import { Sequelize, Model, DataTypes, Op } from 'sequelize';

const sequelize = new Sequelize({
  // database connection configuration
  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()]
    }
  }
})

However, during compilation using tsc, an error was reported:

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.

This error suggests that using Op.between with a date range might not be supported in TypeScript. Strangely, it worked fine when implemented in JavaScript.

I am unsure if there is a flaw in my TypeScript code, a deficiency in the type definition, or if utilizing Op.between with dates is discouraged.

Answer №1

Make sure to pass a string instead of a date object for the createdAt property in Patient.findAll method. Here's how you can do it:

Patient.findAll({
  where: {
    createdAt: {
      [Op.between]: [new Date('2020-02-02').toISOString(), new Date().toISOString()]
    }
  }
})

Answer №2

During my experience, I encountered the following situation:

createdAt: {
        [Op.between]: [
          new Date(startDate).toISOString(),
          new Date(`${endDate} 23:59:59`).toISOString()
        ]
      }

After some experimentation, I found that switching to this code snippet was more effective:

createdAt: {
        [Op.and]: [
          {
            [Op.lt]: new Date(`${endDate} 23:59:59`),
            [Op.gt]: new Date(startDate)
          }
        ]
      }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a MySQL counterpart to Oracle's TIMESTAMP WITH TIME ZONE feature?

Can MySQL provide a similar function as Oracle's TIMESTAMP WITH TIME ZONE? I am trying to convert an Oracle table with columns using that datatype into a MySQL table, but I haven't found a straightforward solution without using certain MySQL fun ...

D3-cloud creates a beautiful mesh of overlapping words

I am encountering an issue while trying to create a keyword cloud using d3 and d3-cloud. The problem I am facing is that the words in the cloud are overlapping, and I cannot figure out the exact reason behind it. I suspect it might be related to the fontSi ...

Utilize the object's ID to filter and display data based on specified criteria

I retrieved an array of objects from a database and am seeking to narrow down the results based on specific criteria. For instance, I want to display results only if a user's id matches the page's correct id. TS - async getResultsForId() { ...

Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me. After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP co ...

Is there a CakePHP field for performing mathematical calculations?

(Looking for a solution similar to Selecting default value in SELECT input with CakePHP) Within my CakePHP project, I have two tables: Trees and Leafs. Each Leaf is associated with a Tree through the tree_id. Additionally, each Leaf has a numeric value. T ...

What is the best way to split a single object into two separate objects based on a specific value within the object using lodash?

Imagine a scenario with an object containing two channels in Dutch (NL) language and one channel in English (EN) language: [ { "name": "De Redactie", "channels": [ { "name": "headlines", "pub ...

Automatically display changes made in MySQL/MariaDB within a React table

In my node.js/express/react/socket.io application, I need to capture data when a button is clicked and insert it into a MySQL/MariaDB table. My query is, Is there a React component that can automatically update itself (showing the table rows from the DB i ...

Mastering the usage of Higher Order Components (HOC) with both types of props is

I am facing a challenge in implementing HOCs for this specific scenario. I aim to enclose existing components since they share similar functionalities. Below is an abridged version of my current structure: function CreateComponentHere(props: BaseProps): J ...

What is the proper way to define the scope for invoking the Google People API using JavaScript?

I am attempting to display a list of directory people from my Google account. export class People { private auth: Auth.OAuth2Client; private initialized: boolean = false; private accessToken: string; constructor(private readonly clientEmail: strin ...

Calculate the total number of entries and generate a numeric list using Laravel

I'm currently working on a project that involves creating a sorting feature. I need to calculate the total number of entries in my database and then display a select dropdown with these entries ordered from 1 to 25. Here's how my controller is s ...

Build a unique array of identifiers extracted from an object

https://i.sstatic.net/PaFXj.png I am seeking advice on how to extract an array of IDs values by iterating through an object in React JS. https://i.sstatic.net/GV6ga.png const initialState = useMemo(()=> { return dataTable.filter(result => f ...

The index signature for strings appears to be duplicated in this TypeScript file, causing an

I am attempting to create a type with an index signature in TypeScript. Here is the code snippet: export interface LoginState { account: { [userName: string]: string; [password: string]: string; }; } However, I ...

Transaction management using stored procedures and PHP Data Objects (PDO)

When executing a single action in PHP, it must follow these steps: Conduct multiple MySQL statements using PHP PDO, based on extensive business logic. Run a stored procedure. Execute additional MySQL statements from PDO. The entire process should be com ...

Switching timezones in PHP programming

Something doesn't quite add up. Let's consider a scenario where my server is set to America/Toronto timezone for storing date/time information. Now, if I need to convert the time for someone on the west coast, I use this code snippet: $timestamp ...

php issue with mysql session

Hey there! I have come across an issue with my code. It works perfectly fine on my localhost, but when I try to run it on my hosting server, it doesn't seem to work properly. I suspect that the problem lies within this particular piece of code: < ...

Issue with saving image in blob field (Integration problem between Angular App and Python)

I am attempting to save an image from my angular App into a mysql blob field using python, however, the image is not saving correctly. This is how I am converting the image to a byte-array: var reader = new FileReader(); reader.readAsArrayBuffer($scope. ...

Error: The reference 'GetServerSideProps' is being incorrectly used as a type instead of a value. Perhaps you intended to use 'typeof GetServerSideProps' instead?

Index.tsx import Image from 'next/image' import Head from "next/head" import { sanityClient, urlFor } from "../sanity" import Link from 'next/link' import {Collection, address} from '../typings'; import ...

Listen for incoming data from the client in the form of an ArrayBuffer

I have been utilizing the ws library within nodejs to develop a small cursor lobby where players can interact. I have managed to utilize the server to send ArrayBuffers with bit streams to the client and successfully decode them. However, I am encountering ...

Setting a dynamically addressed property within a TypeScript interface

I have a situation where I need to dynamically access an object property using a variable that represents a keyof the object type. Here's an example: interface FidelityCheckRow { P1: number; P2: string; P3: string; } const keys: (keyof F ...

Sophisticated SQL query for retrieving date-specific data from a single table

Seeking out an efficient method for querying a MySQL table to extract specific data for each day within a specified date range, where the table contains two date columns indicating start and end dates. Example Table: Promotions Columns: ID startDate ...