我正在尝试通过边做边学来了解 MERN 堆栈如何协同工作,并且我正在遵循 bezcoder 的这些教程:Node.js/Express/MongoDb(Github 整个代码)和 Reactjs(Github 整个代码)
来自服务器的示例数据
[
{
"id": "5f9bdace778082303c859248",
"title": "How to cook noodles",
"description": "This is a tutorial about how to cook noodles in under 10 minutes.",
"published": false
},
{
"id": "5f9bdae3778082303c859249",
"title": "How to bake a chocolate cake",
"description": "This is a tutorial about how to bake chocolate cake using cocoa powder.",
"published": true
}
]
现状 目前,应用程序的前端有一个搜索栏,我可以在其中通过教程的“标题”搜索和过滤数据(例如“面条”以获得第一个)。 我发现这是通过以下代码片段完成的:
exports.findAll = (req, res) => {
const title = req.query.title;
var condition = title ? { title: { $regex: new RegExp(title), $options: "i" } } : {};
Tutorial.find(condition)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving tutorials."
});
});
};
import http from "../http-common";
class TutorialDataService {
...
findByTitle(title) {
return http.get(`/tutorials?title=${title}`);
}
}
export default new TutorialDataService();
我想知道的是,如何更改这些代码,以便我可以按搜索框中的“标题”和“描述”以及published:true中的单词进行过滤通过复选框。
如果前端看起来像这样:
我的尝试
exports.findAll = (req, res) => {
const title = req.query.title || "";
const description = req.query.description || "";
const published = req.query.published;
Tutorial.find(
{
$or: [
{title: { $regex: new RegExp(title), $options: "i"}}, {description: { $regex: new RegExp(description), $options: "i"}}
],
$and: [
.... and here if checked, then only show published, else show all ....
]
}
)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving tutorials."
});
});
};
import http from "../http-common";
class TutorialDataService {
...
findByTitle(title, description, published) {
return http.get(`/tutorials?title=${title}`, `/tutorials?description=${description}`, `/tutorials?published=${published}`);
}
}
export default new TutorialDataService();
我不确定这是否是 findByTitle 的正确用法以及如何正确实现 OR 和 AND 函数。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您的
{中的代码在教程查找查询中出错。$or每个查询都需要单独的{ }。像下面这样使用。它会起作用的。用于在标题、描述和已发布复选框中进行搜索。Tutorial.find:({ $or: [ {title: { $regex: new RegExp(title), $options: "i"}, {description: { $regex: new RegExp(description), $options: "i"} ], published:true })