如何构建一个搜索api,根据关键字查找特定公司?

编程入门 行业动态 更新时间:2024-10-26 04:24:45
本文介绍了如何构建一个搜索api,根据关键字查找特定公司?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试使用 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-18 03:40:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/928388.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:构建一个   关键字   公司   api

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!