Mongoose多个搜索查询参数?

时间:2018-02-13 18:18:34

标签: node.js mongodb mongoose

所以我在表格中实现了一个搜索框,但现在我需要搜索多个字段而不只是schoolName

我到目前为止的代码是以下

router.get('/dashboard', ensureAuthenticated, (req, res) => {
  if (req.query.search) {
    const regex = new RegExp(escapeRegex(req.query.search), 'gi');
    User.find({ schoolName: regex }, function(err, users) {
      res.render('dashboard/index.hbs', {
        pageTitle: 'Dashboard',
        total: users.length,
        users: users
      });
    });
  } else {
    User.find({}, function(err, users) {
      res.render('dashboard/index.hbs', {
        pageTitle: 'Dashboard',
        total: users.length,
        users: users
      });
    });
  }
});

我希望能够按schoolNamecityschoolRepresentativeNameschoolRepresentativeTutorMentor进行搜索

2 个答案:

答案 0 :(得分:1)

您可以使用$or查询来获得所需的结果。

minorLength :: Integer -> Integer
minorLength n = signum r + q + n
   where (q, r) = n `quotRem` 9

答案 1 :(得分:0)

我相信escapeRegex()是为字符串创建正则表达式。

router.get('/dashboard', ensureAuthenticated, (req, res) => {
let query = req.query;
let orquery = [];

for (const key in query) {
    orquery.push({
        key: new RegExp(escapeRegex(query[key]), 'gi')
    });
}
User.find({
    $or: orquery
}, function (err, users) {
    res.render('dashboard/index.hbs', {
        pageTitle: 'Dashboard',
        total: users.length,
        users: users
    });
});

});