-1

i want to filter, but that depend to the user, for example

Data.findAll({
    where: {
        name: {
            [Op.or]: [
                { [Op.like]: ['%samsung%'] },
                { [Op.like]: ['%iphone%'] },
                { [Op.like]: ['%alcatel%']}
            ]
        }
    }
}

If the user selects only Samsung, how do I go about filtering only by Samsung?

3
  • How will you get brand name ? In array or comma separated string. Commented Dec 12, 2021 at 16:34
  • @HassanImam by req.query Commented Dec 12, 2021 at 16:52
  • So I can assume an array then. Right? Commented Dec 12, 2021 at 17:22

1 Answer 1

2

Assuming req.query.brands stores either a single search string or an array of strings we can build Op.or conditions on the fly:

const brands = [].concat(req.query.brands)
const brandConditions = brands.map(x => ({
   [Op.like]: `%${x}%`
})
const foundItems = await Data.findAll({
    where: {
        name: {
            [Op.or]: brandConditions
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.