如何构建一个搜索api,根据关键字查找特定公司? [英] How to build a search api to find a specific company based on a keyword?

查看:33
本文介绍了如何构建一个搜索api,根据关键字查找特定公司?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to build a search api using node.js to query and fetch data from mongodb to be displayed on an ios mobile app. This is my code so far. It is returning all the companies in the database. I only want it to return the top relevant companies when I test it on postman? For example, when I append Goo at the end of url, it should return all companies relevant to it such as google inc, google corp and goo

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

推荐答案

我的建议是使用 RegExp,所以它会是这样的:

My suggestion is to use RegExp, so it would be something like this:

 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 中被视为特殊"字符

But you should keep on mind that you should cover cases when someone tries to "escape" with character such as "*" and "?" because they are considered as "special" chars in RegExp

这篇关于如何构建一个搜索api,根据关键字查找特定公司?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆