简体   繁体   中英

How can I use an array with req.query?

My problem is how can I bring my data structure into the query? I want to be able to search everything via one query. How can I implement this?

I tried to enter the query so =>?basicData.tasks.title=Fleetmanagement. With it I can find all the data that fleet management has in it. But now I want to search with two titles.

Example:

?basicData.tasks.title=Fleetmanagement&basicData.tasks.title=OCPP Backend

But it doesn't work. How can i implement that right?

This is my data structure:

  "basicData": {
      "tasks":[
         {"title": "Fleetmanagement"},
         {"title": "OCPP Backend"}
        ]
    }

My Code:

export const allCompanyData = (req: Request, res: Response) => {
  if (req.query) {
    Company.find(req.query).then(docs => {
      logger.info(`Query works ${req.query}`);
      res.json({
        query: req.query
      })
      res.status(200).json(docs);
    }).catch(err => {
      logger.error(`Error ${err}`);
      res.status(400).json(`Error ${err}`)
    })
  } else {
    Company.find()
      .then((items: any) => {
        logger.info("Successful finding");
        res.status(200).json(items);
      })
      .catch((err: any) => {
        logger.error(`Error ${err}`);
        res.status(400).json(`Error ${err}`);
      });
  }
};

You append [] to the param name on the client side to indicate that you are providing an array:

?basicData.tasks.title[]=Fleetmanagement&basicData.tasks.title[]=OCPP%20Backend

Then req.query will be:

{ 'basicData.tasks.title': ['Fleetmanagement', 'OCPP Backend'] }

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