如何在使用MongoDB分页的数据中实现后端搜索?
我想从分配给用户的SystemID列表中实现同一API中的后端搜索。
将系统(ID)s分配给用户的集合:
{
"_id" : ObjectId("62093266db5c0830fe3397ea"),
"email" : "[email protected]",
"role" : "owner",
"systemID" : [
"12345678",
"20200302"
],
"mobile" : "9876543210"
}
系统ID(BPID)单独存储在另一个包含系统详细信息的集合中。
{
"_id" : ObjectId("6212d42aab85a3b9f7559e02"),
"bPID" : "12345678", // primary key
"bPVoltage" : 45.9,
"capacity" : "5",
"alerts" : [ "201", "342" ],
"state": 2,
"stateOfCharge": 98
},
{
"_id" : ObjectId("6212d42bab8ba3d9f7599ea2"),
"bPID" : "20200302",
"bPVoltage" : 45.9,
"capacity" : "2",
"alerts" : [ "200" ],
"state": 0,
"stateOfCharge": 48
},
{
"_id": ObjectId("6212d42aab85a3b9f7559e02"),
"bPID": "20200302",
"bPVoltage": 45.9,
"capacity": "5",
"alerts": [ "315" ],
"state": 1,
"stateOfCharge": 78
}
现在,我有一张桌子在前端,其中分页的数据被填充在桌子内,上面有一个搜索框。
如果我输入ID,如何实现此搜索,它将返回仅分配给该用户的匹配ID的列表,例如,如果我输入12,则返回了12348或12469分配给用户。我的API代码填充结果仅在表中填充的BPID的结果如下:
router.get('/getActiveSystems', async (req, res) => {
const systemList = req.systemList;
const { page, limit } = req.query;
try {
if (!page || !limit) {
return res.status(400).json({
message: 'Page and limit are required!',
error: true
});
}
const lastTenMinutes = moment().subtract(10, 'm').toDate();
const options = {
page: parseInt(page),
limit: parseInt(limit),
sort: {
date: -1.0
}
};
const query = [
{
$match: {
bPID: {
$in: systemList
},
date: {
$gte: new Date(lastTenMinutes)
}
}
},
{
$project: {
bPID: 1.0,
capacity: 1.0,
alerts: 1.0,
state: 1.0,
stateOfCharge: 1.0
}
}
];
const aggregate = BatteryPacks.aggregate(query);
const systemDetails = await BatteryPacks.aggregatePaginate(aggregate, options);
return res.status(200).json(systemDetails);
} catch (error) {
return res.status(500).json({
message: 'Internal server error'
});
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我正确理解,您可以执行以下操作:
$ match
找到特定用户,$ project
filters仅SystemId
与之匹配的SystemID searchInput和$查找
获得SystemId
数据。还有其他步骤允许分页(在此示例中有10个结果)。您可以看到它在 Playground 上有效
If I understand correctly, you can do something like:
Where the
$match
finds the specific user, the$project
filters onlysystemID
that are matching the searchInput, and the$lookup
gets thesystemID
data. The other steps are there to allow the pagination (of 10 results in this example).You can see it works on the playground