【问题标题】:Fetch data from api(RESTful) db(mongodb) according to user input根据用户输入从 api(RESTful) db(mongodb) 获取数据
【发布时间】:2018-07-22 09:46:50
【问题描述】:

我使用 nodejs、express 和 mongodb 创建了一个 api。我现在正在获取数据而不发送任何查询。但是在我的前端,我有一个输入,用户可以在其中搜索食谱。因此,例如,如果用户键入“今天”,我应该只得到与今天相关的响应。如何在数据库中检查并检索数据?

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);
        }
      });
  });

【问题讨论】:

  • 您是否查看过 express 在线的 API 或大量教程? expressjs.com/en/api.html#req.query。对于 mongo,您已经获得了 find() 方法,只需提供正确的查询

标签: javascript node.js mongodb reactjs express


【解决方案1】:

在进行 api 调用时,将dish 作为查询参数传递

例如'/recipes/?dish="Pizza"'

并在快递中使用以下内容。

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);
        }
      });
  });

【讨论】:

  • Anshul,我的数据对象如下。我必须检查我的对象的标题是否存在该查询。 { "_id": "5b5446df2c89ab3d0e8d5526", "title": "Chicken with Mustard Cream Sauce", "vegetarian": false, "ingredients": [ "4 whole Boneless Skinless Chicken Breasts", ], "image_url": "http://static.food2fork.com/chickenmustarde587.jpg", "steps": [ "Amount of cream and broth has slightly ], "serving": 5, "cooking_time": 20 },
  • 您可以在这种情况下修改您的查询以进行不区分大小写的匹配。更新了答案以反映@BhagyaSwamy
猜你喜欢
  • 2020-08-11
  • 2018-08-24
  • 1970-01-01
  • 2016-09-25
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
相关资源
最近更新 更多