我正在嘗試透過邊做邊學來了解 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 函數。
您的
{中的程式碼在教程尋找查詢中出錯。$or每個查詢需要單獨的{ }。像下面這樣使用。它會起作用的。用於在標題、描述和已發布複選框中進行搜尋。Tutorial.find:({ $or: [ {title: { $regex: new RegExp(title), $options: "i"}, {description: { $regex: new RegExp(description), $options: "i"} ], published:true })