【问题标题】:Fetching data using sequalise in which the date is lesser than that of now date使用日期小于现在日期的sequelize获取数据
【发布时间】:2026-02-07 00:55:01
【问题描述】:

这是我的小提琴。 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 上的日期类型。

【问题讨论】:

    标签: node.js sequelize.js psql


    【解决方案1】:

    这可能是因为 $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

    【讨论】:

      【解决方案2】:

      如果您使用的是 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
          });
      

      【讨论】:

        最近更新 更多