node.js - 使用 sequelize 进行子查询以使用日期和时间过滤即将发生的事件

标签 node.js postgresql express sequelize.js

谁知道如何使用 sequelize 查询即将发生的事件? 我想要一种情况,一旦事件开始 (事件日期 >= 今天的日期和事件时间 >= 今天的时间),它就会从“即将发生的事件”列中删除 我试过了

db.Event.findAll({
     where: {
        [db.Sequelize.Op.and]: [{ isPrivate: false },
            { startdate: { $gte: new Date().toLocaleDateString() } },
            { starttime: { $gt: new Date().toLocaleTimeString('en-GB') } }
        ]
     }, 
     include: [{
       model: db.Center,
       attributes: ['id', 'name', 'location']
     }],
     order: [
       ['startdate', 'ASC'],
       ['starttime', 'ASC']
     ]
})
    .then((events) => {
     res.status(200).json({
         success: 'ok',
         data: events
    });
})
  .catch((err) => {
    res.status(500).json({
      message: err.message || 'Internal server error',
    });
});

但它不起作用,有人告诉我为什么它不起作用。 我需要一种方法来过滤掉 WHEN (startdate >= new Date().toLocaleDateString()) 的时间。我徒劳地试图找出它是如何工作的。请帮忙。

最佳答案

const dateOfToday = new Date();
const timeOfToday = moment().format('HH:mm:ss');

const daysEqualToToday = db.Event.findAll({
  where: {
    startdate: { $eq: dateOfToday },
  },
  include: [{
    model: db.Center,
    attributes: ['id', 'name', 'location']
  }],
  order: [
    ['startdate', 'ASC'],
    ['starttime', 'ASC']
  ]
})
  .then(events =>
    events.filter(event => event.starttime > timeOfToday));


const daysGreaterThanToday = db.Event.findAll({
  where: {
    startdate: { $gt: dateOfToday },
  },
  include: [{
    model: db.Center,
    attributes: ['id', 'name', 'location']
  }],
  order: [
    ['startdate', 'ASC'],
    ['starttime', 'ASC']
  ]
});


Promise
  .all([daysEqualToToday, daysGreaterThanToday])
  .then((results) => {
    const combinedResult = [].concat(...results);
    res.status(200).json({
      success: 'ok',
      data: combinedResult
    });
  })
  .catch((err) => {
    res.status(500).json({
      message: err.message || 'Internal server error',
    });
  });
 }

因此,我无法使用 sequelize 子查询来解决我的问题。我得到了一个建议(不是来自 stackoverflow),将我的日期保存为数据库中的日期时间,并使用它来比较直接查询数据库两次的日期时间。我决定反对它,因为我觉得它不利于用户体验。

我最终决定采用一个不太理想的解决方案。对数据库进行两次查询 第一个:当开始日期与今天相同时进行查询,然后过滤开始时间以查找大于今天时间的开始时间。

第二个:当开始日期大于今天时进行查询。

然后我使用 Promise.all 来解决这两个查询。就像我说的,这个解决方案不太理想,因为我对数据库进行了两次调用,但我现在会使用它。我将欣赏更好的实现方式。

关于node.js - 使用 sequelize 进行子查询以使用日期和时间过滤即将发生的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50549384/

相关文章:

javascript - 如何使用 Node.js 将变量传递给 Jade 中的页脚

javascript - Firebase:如何通过nodemailer发送的电子邮件模板发送重置链接?

python - SQLAlchemy 级联删除到多对多表

SQL SELECT 排除具有任何值列表的行?

jquery - 如何在 Express View 之间进行页面转换?

node.js - 使用 process.on('uncaughtException 显示 500 错误页面

Javascript/Sails.js Controller 等待服务调用异步函数

node.js - Node.js非阻塞for循环

sql - 在 Sequelize 模型中使用 Postgres 生成的列

Node.js/Express 本地磁盘缓存