LIKE for timestampz sequelize

Asked

Viewed 102 times

-2

I am trying to filter the activities by date but the field is timestampz. The bank I am using is the postgres

{
  "name": "SequelizeDatabaseError",
  "parent": {
    "name": "error",
    "length": 220,
    "severity": "ERROR",
    "code": "42883",
    "hint": "No operator matches the given name and argument types. You might need to add explicit type casts.",
    "position": "82",
    "file": "parse_oper.c",
    "line": "731",
    "routine": "op_error",
    "sql": "SELECT \"id\", \"operation\" FROM \"activities\" AS \"Activity\" WHERE \"Activity\".\"date\" LIKE '2020-02-25%';"
  },

Code:

async index(req, res) {
    await Activity.findAll({
      attributes: ['id', 'operation'],
      where: {
        date: {
          [Op.startsWith]: req.body.date,
        },
      },
    })
      .then(activities => {
        return res.json(activities);
      })
      .catch(err => {
        return res.status(400).json(err);
      });
  }

With this query I can filter but no sequelize:

SELECT * from activities WHERE date::text LIKE '2020-02-25%'
  • 1

    The operator LIKE in SQL is an operator between strings and not another type of data.

1 answer

0

I resolved with the between using a lib for date manipulation called date-fns.

import { Op } from 'sequelize';
import { startOfDay, endOfDay, parseISO } from 'date-fns';

import Activity from '../models/Activity';

class Controller {
  async index(req, res) {
    await Activity.findAll({
      attributes: ['id', 'operation'],
      where: {
        date: {
          [Op.between]: [
            startOfDay(parseISO(req.body.date)),
            endOfDay(parseISO(req.body.date)),
          ],
        },
      },
    })
      .then(activities => {
        return res.json(activities);
      })
      .catch(err => {
        return res.status(400).json(err);
      });
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.