简体   繁体   English

根据用户输入从api(RESTful)db(mongodb)中获取数据

[英]Fetch data from api(RESTful) db(mongodb) according to user input

I have created an api using nodejs, express and mongodb. 我已经使用nodejs,express和mongodb创建了一个api。 I am fetching data now without sending any query. 我现在正在获取数据而没有发送任何查询。 But in my frontend I have an input where the user can search for a recipe. 但是在我的前端,我有一个输入,用户可以在其中搜索食谱。 So for example if a user types "Today" i should get response related to today only. 因此,例如,如果用户键入“ Today”,则我应该只获得与今天相关的响应。 How to check that in db and retrieve data? 如何在db中检查和检索数据?

module.exports = function(app, db) {
  app.get("/dates/", (req, res) => {
    db
      .collection("dates")
      .find()
      .toArray((err, item) => {
        if (err) {
          res.send({ error: "An error has occured" });
        } else {
          res.send(item);
        }
      });
  });

While making the api call , pass the dish as query parameter 在进行api调用时,将dish作为查询参数

For example '/recipes/?dish="Pizza" ' 例如'/ recipes /?dish =“ Pizza”'

and in the express use the following. 并明确使用以下内容。

module.exports = function(app, db) {
  app.get("/recipes/", (req, res) => {
    let queryDish = req.query.dish; // assuming /recipes/?dish="Pizza"
    let query = { 'title' : { '$regex' : queryDish, '$options' : 'i' } }; 
    db
      .collection("recipes")
      .find(query)
      .toArray((err, item) => {
        if (err) {
          res.send({ error: "An error has occured" });
        } else {
          res.send(item);
        }
      });
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM