如何在mongodb中只用一个搜索字符串搜索多个字段

时间:2021-03-24 08:59:38

标签: node.js mongodb mongoose

我的前端有一个表,它显示用户列表并包含多列以显示每行的数据,即名字、姓氏、电话和电子邮件。对于在后端使用查询的表,我还有一个分页和搜索栏。我几乎已经弄清楚了分页,但到目前为止我还无法使用在搜索栏中输入的“搜索字符串”来查询用户数据。我只从前端收到一个搜索字符串,我必须根据搜索字符串搜索用户。 因此,“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 });
}

}

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

0 个答案:

没有答案
相关问题