Узел частичного поиска - PullRequest
0 голосов
/ 06 июля 2019

Я нашел учебник в Интернете, и есть простой способ сделать частичный поиск.Что я хочу сделать, так это когда кто-то пишет только geor, он найдет пользователя с именем george

db.stores.find({storeName : {$regex : /Geor/}}).pretty()

Но я не знаю, как реализовать это в своем поиске.Я попробовал несколько вещей, но все заканчивается ошибками.

Вот мой контроллер:

/**
 * GET /admin/users/:page
 * Find users
 */
exports.findUsers = (req, res, next) => {
  const perPage = 13
  const page = Number(req.params.page) || 1

  var query = {};

  const possibleQueryProps = [{
      "key": "id",
      "queryKey": "_id"
    },
    {
      "key": "email",
      "queryKey": "email"
    },
    {
      "key": "firstname",
      "queryKey": "profile.firstname"
    },
    {
      "key": "lastname",
      "queryKey": "profile.lastname"
    },
    {
      "key": "location",
      "queryKey": "profile.location"
    },
    {
      "key": "status",
      "queryKey": "profile.status"
    }
  ];

  possibleQueryProps.forEach(prop => {
    if (req.query[prop.key]) {
      query[prop.queryKey] = req.query[prop.key];
    }
  });
  console.log(query)
  User
    .find(query)
    .skip((perPage * page) - perPage)
    .limit(perPage)
    .exec(function (err, users) {
      User.countDocuments(query).exec(function (err, count) {
        if (err) return next(err)
        res.render('admin/users', {
          layout: "admin",
          users: users,
          query: req.query,
          active: {
            users: true
          },
          current: page,
          pages: Math.ceil(count / perPage),
          helpers,
          pagesArr: Array.from(Array(((Math.ceil(count / perPage)))).keys()).map(i => 1 + i),
          pagination: core.pagination(page, (Math.ceil(count / perPage))),
        })
      })
    })
};

Буду благодарен за любой совет.

1 Ответ

1 голос
/ 06 июля 2019

Я думаю, что это будет работать:

possibleQueryProps.forEach(prop => {
  if (req.query[prop.key]) {
    query[prop.queryKey] = {$regex : new RegExp('.*' + req.query[prop.key] + '.*')};
  }
});
...