首页 > 解决方案 > 如何在正则表达式中使用 request.query

问题描述

我有这个搜索控制器,我想将其设置为检查搜索输入中的每个字母,但我不知道如何使用正则表达式。

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);
}

另外,我尝试过

{ firstName: /req.query.search/ }

,但它不起作用。任何帮助都会很棒。

标签: node.jsregexmongodbexpress

解决方案


我找到了解决方案。我需要创建函数来放置整个正则表达式,然后在控制器内部将 req.query 传递给它

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, "\\$&");
}

推荐阅读