首页 > 解决方案 > 如何在mongodb中仅使用一个搜索字符串搜索多个字段

问题描述

我的前端有一个表格,它显示了一个用户列表,并包含多个列来显示每一行的数据,即名字、姓氏、电话和电子邮件。对于在后端使用查询的表,我还有一个分页和搜索栏。我几乎已经弄清楚了分页,但到目前为止我无法使用在搜索栏中输入的“搜索字符串”来查询用户数据。我只从我的前端收到一个搜索字符串,我必须根据搜索字符串搜索用户。因此,“martha/mar/marth”将返回名为 martha 的用户,而“clark@gmail.com”将返回该用户的电子邮件以及找到的任何其他匹配项。如果搜索字符串为空 (""),则应返回所有数据。

async getUserList(req, res) {
let { page, limit, search } = req.query;
console.log(page, limit, search);

//Get pagination params
limit = parseInt(limit);
const offset = parseInt(page - 1) * limit;

//Get users
try {
  let users = await UserSchema.aggregate([
    {
      $match: {
        $text: { $search: search },
      },
    },
    {
      $facet: {
        data: [
          { $sort: { createdAt: -1 } },
          { $skip: offset },
          { $limit: limit },
        ],
        count: [
          { $group: { _id: null, total: { $sum: 1 } } },
          { $project: { _id: 0 } },
        ],
      },
    },
  ]);

  res.status(200).json({
    messsage: "User list",
    totalRecords: users[0].count.length ? users[0].count[0].total : 0,
    data: users[0].data,
  });
} catch (error) {
  console.log(error);
  res.status(400).json({ error: error || error.message });
}

}

到目前为止,我已经通过为可搜索列创建文本索引来尝试进行文本搜索,但它在搜索时出现了意外行为并且没有返回它应该返回的数据。

标签: node.jsmongodbmongoose

解决方案


推荐阅读