【问题标题】:How to build a search api to find a specific company based on a keyword?如何构建搜索 api 以根据关键字查找特定公司?
【发布时间】:2017-12-05 14:44:27
【问题描述】:

我正在尝试使用 node.js 构建一个搜索 api,以从 mongodb 查询和获取数据以显示在 ios 移动应用程序上。到目前为止,这是我的代码。它正在返回数据库中的所有公司。我只希望它在我在邮递员上测试时返回顶级相关公司?例如,当我在 url 末尾附加 Goo 时,它应该返回与其相关的所有公司,例如 google inc、google corp 和 goo

 api.get('/search/:name',(req,res) => {
    Company.find(req.params.name, (err, company) => {
      if(err){
        res.send(err);
      }
        res.json(company);
    });
});

【问题讨论】:

  • 尝试阅读核心文档中的Query Documents,了解您查询某些属性的方式。

标签: node.js mongodb api mongoose


【解决方案1】:

我的建议是使用 RegExp,所以应该是这样的:

 api.get('/search/:name',(req,res) => {
    Company.find({insert name of your field here: new RegExp('^' + req.params.name + '$', "i"), (err, company) => {
      if(err){
        res.send(err);
      }
        res.json(company);
    });
});

但是你应该记住,当有人试图用“*”和“?”之类的字符“逃脱”时,你应该涵盖这些情况。因为它们在 RegExp 中被视为“特殊”字符

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2011-04-05
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    相关资源
    最近更新 更多