0

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 Answers2

1

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.

Alex Blex
  • 34,704
  • 7
  • 48
  • 75
  • Thank you! I know that i can do conversion, but it looks not so pretty. May be exist npm package to make it automatically or any other more beautiful way, other than vanilla js? – Dmitry Borisenko Jul 24 '23 at 11:41
  • Yes there are packages for that e.g. zod, joi – Konrad Jul 24 '23 at 11:47
  • Agree, if you are using express, you probably want a middleware wrapper for zod or other libs. I personally wouldn't bother, but aesthetic of a solution is always a controversial topic, so I'll leave it with you to decide. – Alex Blex Jul 24 '23 at 12:52
0

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