【问题标题】:Node partial search节点部分搜索
【发布时间】:2019-07-06 06:25:30
【问题描述】:

我在网上找到了一个教程,并且有一种简单的方法可以进行部分搜索。我想要做的是当有人只写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))),
        })
      })
    })
};

如果您有任何建议,我将不胜感激。

【问题讨论】:

  • 你遇到了什么错误?
  • @CuongLeNgoc 取决于我把 $regex 放在哪里我试图把它放在任何地方但不知道它应该在哪里或者是否足以只放 $regex。我还是节点的新手。我发布的控制器代码工作正常,但我需要以某种方式实现部分搜索。
  • 你想用正则表达式搜索所有道具吗?
  • 是的,如果我认为是正则表达式,那么是的。

标签: javascript node.js regex search partial


【解决方案1】:

我认为它会起作用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    相关资源
    最近更新 更多