【问题标题】:How to query a mongodb with nodejs for a case insensitive search/string containing substring search如何使用nodejs查询mongodb以进行不区分大小写的搜索/包含子字符串搜索的字符串
【发布时间】:2020-10-12 20:00:33
【问题描述】:

所以我想在我的数据库中搜索职位名称。但是,只有在确切的字符串匹配时才有效,我希望搜索不区分大小写,并且如果 ti 包含一些搜索查询,则可以在数据库中找到字符串。

我环顾四周,发现正则表达式可能适用于大小写问题,但我不确定如何使用已有的实现它。

Jobs.route

router.get("/search", async (req, res) => {

let query = {}; 

let tmp = req.query;


if (tmp && tmp != undefined && Object.keys(tmp).length != 0) {
    query = tmp;
}   

let jobs = await Job.find(query)
    .sort({ createdAt: -1 }); 

if (!jobs) {
    return res.status(400).send({
        message: `Encountered an error when getting job with title ${req.query.title}.`,
        ok: false,
        errors: [error],
        jobs: {}
    });
} else {
    return res.send({
        total_items: jobs.length,
        message: `Returned all jobs with title ${req.query.title} successfully`,
        ok: true,
        errors: [],
        jobs: jobs
    });
}
});

module.exports = router;

【问题讨论】:

  • 请提供req.query

标签: node.js mongodb api


【解决方案1】:

首先,您必须向集合添加索引 ($text)。

参考:https://docs.mongodb.com/manual/reference/operator/query/text/

db.articles.createIndex( { subject: "text" } )

完成后,将查询更新为

Jobs.find({ $text: { $search: "Developer" } }) //Software being the Job Title

在当前代码中:req.query -> "{ $text: { $search: "Developer" } }";

这将帮助您获得具有匹配标题的文档,例如 ->

[ "SOFTWARE DEVELOPER", "Software Developer", "software developer" , "SoftWare DeveLoPer" , "BackEnd Developer" , "Developer In Test" ....]

【讨论】:

    猜你喜欢
    • 2012-04-28
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    相关资源
    最近更新 更多