skip to Main Content

Back end (nodejs)

async getAllEvents(req, res, database, collection) {
    try {
      const { filter, sort } = req.query;

      const events = await mongo
        .getClient()
        .db(database)
        .collection(collection)
        .find(filter)
        .sort(sort)
        .toArray();

      res.json(events);
      res.end();
    } catch (error) {
      return res.status(400).json({ message: "err_get_events" });
    }
  }

Front end (react)

const getAllEvents = async () => {
    const query = settings.query;
    await axios
      .get(Constants.BASE_URL + '/' + settings.urlprefix + '/get', { params: { filter: { helped: true }, sort: { dateAdded: -1 } } })
      .then((res) => {
        setEvents(res.data);
      })
      .catch((err) => console.log(err?.response?.data?.message));
  };

on backend i got from console.log: { filter: { helped: 'true' }, sort: { dateAdded: '-1' } } and helped and sort become string

When i pass { helped: 'true' } to mongo .find() not give any results, because in mongo i store boolean.

How can i got correct types of variables on the back end side after query parsing?

2

Answers


  1. Chosen as BEST ANSWER

    Initially, I wanted to use a NPM package to convert all received json, to make it automatically and avoid any future care about backend code. But apparently i did not have the patience to dwell on this problem further. And i made temporuary solution:

    async getAllEvents(req, res, database, collection) {
        try {
          const { filter, sort } = req.query;
    
          if (filter) filter.helped = JSON.parse(filter.helped);
          if (sort) sort.dateAdded = JSON.parse(sort.dateAdded);
    
          const events = await mongo
            .getClient()
            .db(database)
            .collection(collection)
            .find(filter)
            .sort(sort)
            .toArray();
    
          res.json(events);
          res.end();
        } catch (error) {
          return res.status(400).json({ message: "err_get_events" });
        }
      }
    

  2. The boolean becomes a string long before it is sent to mongo. HTTP is a text based protocol, whatever you send in the URL as a GET parameter is a string, and it’s server’s responsibility to convert it to appropriate data type.

    Please read How can I convert a string to boolean in JavaScript? for inspiration how to do the conversion suitable to your usecase.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search