使用Mongodb进行模糊搜索?

And*_*rdi 13 search mongoose mongodb

我已经设法在我的mongodb应用程序中设置搜索功能.请参阅下面的代码.这非常有效,但它只返回确切的结果.如何更改代码以使其接受更"模糊"的搜索结果?谢谢!

router.get("/", function(req, res){
    if (req.query.search) {
       Jobs.find({"name": req.query.search}, function(err, foundjobs){
       if(err){
           console.log(err);
       } else {
          res.render("jobs/index",{jobs:foundjobs});
       }
    }); 
    }

  Jobs.find({}, function(err, allJobs){
       if(err){
           console.log(err);
       } else {
          res.render("jobs/index",{jobs:allJobs});
       }
    });
});
Run Code Online (Sandbox Code Playgroud)

the*_*lla 27

我相信要进行"模糊"搜索,你需要使用正则表达式.这应该完成你正在寻找的东西(这里是escapeRegex函数源):

function escapeRegex(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};

router.get("/", function(req, res) {
    if (req.query.search) {
       const regex = new RegExp(escapeRegex(req.query.search), 'gi');
       Jobs.find({ "name": regex }, function(err, foundjobs) {
           if(err) {
               console.log(err);
           } else {
              res.render("jobs/index", { jobs: foundjobs });
           }
       }); 
    }
}
Run Code Online (Sandbox Code Playgroud)

话虽这么说,您的应用程序在使用正则表达式查询mongo时可能会遇到性能问题.使用搜索索引等库进行搜索可以帮助优化应用程序的性能,还可以搜索词干(例如从"查找"返回"找到").


更新:我的原始答案包括一个简单的常规扩展,使您的应用程序容易受到正则表达式DDoS攻击.我已经更新了"安全"转义的正则表达式.

  • @AndrewLeonardi只是检查你已经看到我更新的答案......我不希望你的应用程序容易受到正则表达式DDoS攻击! (5认同)

Vas*_*las 13

我知道这是一个旧线程,但我制作了一个基于这篇文章的插件。

猫鼬模糊搜索

(它使用$text查询运算符代替$regex,以获得更快的结果)

下面的例子只是根据标题和城市搜索事件

const mongoose_fuzzy_searching = require('mongoose-fuzzy-searching');

const schema = {
    title: {
        type: String,
        trim: true,
        required: true,
    },
    description: {
        type: String,
        trim: true,
    },
    city: {
        type: String,
    },
    address: {
        type: String,
    }
};

const EventsSchema = mongoose.Schema(schema);
EventsSchema.plugin(mongoose_fuzzy_searching, {fields: ['title', 'city']});

const Events = mongoose.model('Events', EventsSchema);

Events.fuzzySearch('Nodejs meetup').then(console.log).catch(console.error);
Run Code Online (Sandbox Code Playgroud)