Myrmelo
Myrmelo

Reputation: 83

How to make sequelize query case insensitive?

I have the following code :

module.exports.MyFunction= async (req, res) => {
  let token = req.body.token;
  let decoded = jwt_decode(token);
  let loggedUserEmail = decoded.email;
  let data = req.body;
  let searchUser = data.user;
  console.log(searchUser);

  try {
    let user = await User.findAll({
      where: {
        [Op.or]: [
          {
            firstName: {
              [Op.startsWith]: searchUser,
            },
          },
          {
            lastName: {
              [Op.startsWith]: searchUser,
            },
          },
          {
            email: {
              [Op.startsWith]: searchUser,
            },
          },
          {
            publicKey: {
              [Op.startsWith]: searchUser,
            },
          },
        ],
        email: {
          [Op.ne]: loggedUserEmail,
        },
      },
      attributes: ["firstName", "lastName", "email", "publicKey", "avatar"],
    }).then((response) => {
      return response;
    });

    res.json({ user });
  } catch (err) {
    res.json({ err });
  }
};

It works well and give me all the users that match with searchUser value. What I need is to get the same results if searchUser is "Michel" or "michel" for instance.

How do I make that case insensitive ?

Upvotes: 0

Views: 203

Answers (1)

Rokas Rudys
Rokas Rudys

Reputation: 481

There is a choice:

  • Either store data/convert data in UPCASE/DOWNCASE and them do the same to input then search
  • use case insensitive iLike which would become [Op.iLike] and then add % at the end of the searchUser if youd like to match similarly to your startsWith

Upvotes: 1

Related Questions