0

I have this search controller and I want to set it up to check every letter in search input but I don't know how to do it with regex.

module.exports.search = (req, res, next) => {
  Character.find({
    $or: [
      { firstName: req.query.search },
      { lastName: req.query.search }
    ]
  })
    .then(characters => {
      res.status(200).send(characters);
    })
    .catch(next);
}

Also, I have tried with

{ firstName: /req.query.search/ }

, but it doesn't work. Any help would be great.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Opie Winston
  • 69
  • 2
  • 10
  • 1
    See https://stackoverflow.com/questions/49270331/use-javascript-variable-as-a-value-of-regex-in-mongodb-query and also https://stackoverflow.com/questions/10728043/mongo-query-with-regex-in-node-js-operating-on-a-variable – Wiktor Stribiżew Nov 05 '19 at 11:51
  • are you getting req.query.search or not ??? – Prakash Karena Nov 05 '19 at 11:55
  • @PrakashKarena I am not getting anything when I use regex. req.query.search works perfectly fine without it, but I need to check all letters from the query, not just full string. I hope I explained it well – Opie Winston Nov 05 '19 at 11:57

1 Answers1

0

I found a solution. I needed to create function to place the whole regex, and then to pass req.query to it inside of controller

module.exports.search = (req, res, next) => {
  if (req.query.search) {
    const regex = new RegExp(escapeRegex(req.query.search), "gi");

    Character.find({
      $or: [{ firstName: regex }, { lastName: regex }]
    })
      .then(characters => {
        res.status(200).send(characters);
      })
      .catch(next);
  }
};

function escapeRegex(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Opie Winston
  • 69
  • 2
  • 10