javascriptmysqlexpressbooleantinyint

How to convert TINYINT(1) to BOOLEAN in express?


I have some columns (infected and absence) in my MySQL database that are stored as TINYINT(1).

When I do a simple

app.get("/users", (req, res) => {
  const sql = `SELECT * from users`;
  connection.query(sql, (err, results) => {
    if (err) {
      return res.send(err);
    } else {
      return res.json({ results });
    }
  });
});

in my backend and a

  useEffect(() => {
    axios
      .get(`${config.server}/users`)
      .then((result) => {
        setUsers(result.data.results);
      })
      .catch((error) => console.error(error));
  }, [setUsers]);

in my ReactJS frontend, I am not able to do something like:

users.filter((u) => u.infected);

Only

users.filter((u) => u.infected === 1);

is working.

As using users.filter((u) => u.infected); is more intuitive for me, I want to know, how can I handle this in best practice?

  1. Do I need to store my values in another type?
  2. Do I need to SELECT the values in a different way?
  3. Do I need to translate the values from 1 to TRUE and 0 to FALSE after querying them?
  4. Do I need to translate the values in the frontend after the get request?

I try to avoid using 4. unless this is not the best deal, because my frontend already expects booleans all over the place (I switched the database to MySQL).


Solution

  • Try using !! they will convert the value to a boolean type. It's equivalent with: Boolean(anyValue).

    users.filter(u => !!u.infected);