简体   繁体   中英

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

I have created an api using nodejs, express and mongodb. 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. How to check that in db and retrieve data?

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

For example '/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);
        }
      });
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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