node.js - 如何在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 });
}
}
到目前为止,我已经通过为可搜索列创建文本索引来尝试进行文本搜索,但它在搜索时出现了意外行为并且没有返回它应该返回的数据。
解决方案
推荐阅读
- python - 在 bat 脚本中运行 python 脚本
- c# - 如何在 Xamarin Forms 中使用 ControlTemplate 进行替代绑定
- android - 片段或活动中的休息调用和 SQLite.NET
- python - 存储和保存多维数据集的最佳方法是什么
- reactjs - 使用 Dex 进行调试转换类导致 Windows 崩溃
- r - 在函数中使用省略号使用 tidy 原则读取数据
- python - DoCplex 中的 Bass 模型:如何在约束中分配变量
- azure - 指向 Azure 负载均衡器公共 IP 的 Azure 前门后端池未解析
- node.js - React-Admin:`make` 命令失败
- javascript - JavaScript - 我怎样才能让它更动态?