使用sequelize获取日期小于现在日期的数据

Fetching data using sequalise in which the date is lesser than that of now date

这是我的Fiddle。 http://sqlfiddle.com/#!17/20c29

我正在尝试获取日期小于当前日期的行。我的Node js代码如下

let nowDate = moment().startOf('day').subtract(7, 'days').toDate();
        console.log(nowDate);
        const campaign = await Campaigns.findAll({
            where: {
                campaign_end_date: {
                    $lt: nowDate
                  }
            },
            attributes: ['campaign_id',  'campaign_end_date'],
            required: true
        });

这没有返回任何数据,我该怎么做?我无法更改 psql 上的日期类型。

可能是因为语法 $lt 已弃用,需要特定配置才能使用。

这是文档中讨论这个的部分。

Deprecated: Operator Aliases
In Sequelize v4, it was possible to specify strings to refer to operators, instead of using Symbols. This is now deprecated and heavily discouraged, and will probably be removed in the next major version. If you really need it, you can pass the operatorAliases option in the Sequelize constructor.

For example:

const { Sequelize, Op } = require("sequelize");
const sequelize = new Sequelize('sqlite::memory:', {
  operatorsAliases: {
    $gt: Op.gt
  }
});

// Now we can use `$gt` instead of `[Op.gt]` in where clauses:
Foo.findAll({
  where: {
    $gt: 6 // Works like using [Op.gt]
  }
});

那么你可以尝试使用新语法吗? 应该是这样的:

campaign_end_date: {
                    [Op.lt]: nowDate
                  }

注意之前需要导入Op

仅供参考,属性 required 不能在此处使用。 它只是在进行预先加载时(在 include 内)用于将内部连接转换为左连接(在 SQL 的观点中)。

如果您有兴趣,这里是讨论它的文档: https://sequelize.org/master/manual/eager-loading.html

如果您使用的是 Sequelize v5,则必须包含 Op,因为密钥已移至 Symbol

const { Op } = require('sequelize')

const campaign = await Campaigns.findAll({
        where: {
            campaign_end_date: {
                [Op.lt]: nowDate
              }
        },
        attributes: ['campaign_id',  'campaign_end_date'],
        required: true
    });