JavaScript - Trying to filter data

Viewed 55

thank you for answer, the problem has been resolved

1 Answers

An SQL LIKE "" is looking for empty values.

So you need to send a different WHERE clause to the DB if there is no title in the request.

//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."
      });
    });
};
Related