【问题标题】:JavaScript - Trying to filter dataJavaScript - 试图过滤数据
【发布时间】:2021-08-24 01:14:11
【问题描述】:

谢谢解答,问题已解决

【问题讨论】:

  • 闻起来像代码请求。
  • 两者都有效,但不是一个。我想我错过了一些非常简单的东西。
  • 你读过我发布的任何东西吗?
  • 您需要在某处使用if 语句来检查title 是否为空。你有没有尝试过?
  • 我认为 where-title 末尾的“||”)可以处理该部分。

标签: javascript api express


【解决方案1】:

一个 SQL LIKE "" 正在寻找空值。

因此,如果请求中没有title,则需要向数据库发送不同的WHERE clause

//Finds All of the User's Cards, and allows Searching by Title
exports.findMyCards2 = (req, res) => {
  const { page, size, title, authorid } = req.query;
  const { limit, offset } = getPagination(page, size);
  
  // Your default query
  let query = {
    authorid: { [Op.like]: `%${authorid}%` },
    title: { [Op.like]: `%${title}%`}
  }

  // Query if the title is undefined (Remove the a title criteria of the WHERE)
  if(!title){
    query = {
      authorid: { [Op.like]: `%${authorid}%` }
    }
  }
  
  Card.findAndCountAll({
    limit,
    offset,
    where: query  // Then use it here
  })
    .then(data => {
      const response = getPagingData(data, page, limit);
      res.send(response);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving Cards."
      });
    });
};

【讨论】:

  • 这对我来说看起来不错,但如果我只有作者,它仍然不起作用。我仍然得到零结果。
  • 在没有标题的情况下你能控制台记录title吗?是空字符串还是undefined?如果是这样...只需更改条件;)
  • 那么if(!title){就可以了
  • 这似乎成功了!我正在测试它,一切都像我希望的那样工作。我真的很感谢你的帮助,我很抱歉在介绍中没有更清楚。非常感谢!
猜你喜欢
  • 2019-04-29
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 2021-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多