我想制作不區分大小寫的搜索 API(我使用的是 Express、Mongoose 和 Angular)。我的 Angular 應用程式和輸入欄位中有資料表。所以我的 API 應該通過 (onChange) 回傳資料。我有兩個集合(容器和容器型別)。我希望它與此示例完全相同:https ://www.w3schools.com/jquery/jquery_filters.asp?fbclid=IwAR3klbA6BJQ_a3wTRf8legaucd4S_2Ns6j8QGQjElgVCrEbde6HT3DSZz38
此搜索 API 向我回傳正確的資料欄位(所有者、標識號和制造商,它們在單獨的集合中,但我成功地從其他集合中獲取)。但是我列出的這個 API 在我寫 FULL STRING 時會回傳資料,它不能通過寫信來作業。
router.get("/search", async (req, res) => {
try {
const { searchString } = req.body;
const containers = await Container.aggregate([
{
$lookup: {
from: "containerstypes",
localField: "containerTypeID",
foreignField: "_id",
as: "containerTypes",
},
},
{ $unwind: "$containerTypes" },
{
$match: {
$or: [
{ owner: searchString },
{ IdentificationNo: searchString },
{ "containerTypes.manufacturer": searchString },
],
},
},
]);
res.status(200).json(containers);
} catch (err) {
res.status(404).json({ success: false, msg: "Container not found" });
}
});
感謝大家的幫助。我在這里使用了聚合,但如果可能的話,我可以在沒有聚合框架的情況下制作它。為了僅在我的表中列出資料,我使用了查找和填充函式。
uj5u.com熱心網友回復:
最好在要搜索的欄位上創建文本索引。在您的模型檔案中,您可以通過這種方式創建索引,
schema.index({owner: 'text', IdentificationNo: 'text'});
schema.index({'containerTypes.manufacturer': 'text'});
搜索使用$text和$search運算子,
await Container.find({$text: {$search: searchString }});
這里的問題是您不能在聚合函式中使用 $text,它只允許作為管道中的第一階段,這對您的情況沒有用處。
如果可能的話,我建議將 containersType 集合嵌入到容器集合中
uj5u.com熱心網友回復:
我找到了解決方案。我只是在每個 SearchString 之前包含了 $regex。現在它可以作業,但我會很感激,因為我沒有太多現實世界的經驗,如果有人能告訴我,這是否是一個好的解決方案。
router.get("/search", async (req, res) => {
try {
const { searchString } = req.body;
const containers = await Container.aggregate([
{
$lookup: {
from: "containerstypes",
localField: "containerTypeID",
foreignField: "_id",
as: "containerTypes",
},
},
{ $unwind: "$containerTypes" },
{
$match: {
$or: [
{ owner: { $regex: searchString, $options: "i" } },
{ IdentificationNo: { $regex: searchString, $options: "i" } },
{
"containerTypes.manufacturer": {
$regex: searchString,
$options: "i",
},
},
],
},
},
]);
res.status(200).json(containers);
} catch (err) {
res.status(404).json({ success: false, msg: "Container not found" });
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/484517.html
上一篇:如何過濾查找mongodb的結果
下一篇:字典串列中的Python匹配鍵
