[英]How do you perform a Case-Insensitive query in node.js implementations of mongodb?
[英]Node.js Express case-insensitive search (filter) through MongoDB database
我想制作不区分大小写的搜索 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" });
}
});
感谢大家的帮助。 我在这里使用了聚合,但如果可能的话,我可以在没有聚合框架的情况下制作它。 为了仅在我的表中列出数据,我使用了查找和填充函数。
我找到了解决方案。 我只是在每个 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" });
}
});
最好在要搜索的字段上创建文本索引。 在您的模型文件中,您可以通过这种方式创建索引,
schema.index({owner: 'text', IdentificationNo: 'text'});
schema.index({'containerTypes.manufacturer': 'text'});
使用$text
和$search
运算符进行搜索,
await Container.find({$text: {$search: searchString }});
这里的问题是您不能在聚合函数中使用 $text,它只允许作为管道中的第一阶段,这对您的情况没有用处。
如果可能的话,我建议将 containersType 集合嵌入到容器集合中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.