When i parse by req.query boolean and number to json it becomes string. Mongo .find() finds nothing

huangapple go评论65阅读模式
英文:

When i parse by req.query boolean and number to json it becomes string. Mongo .find() finds nothing

问题

以下是您要翻译的代码部分:

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

在后端控制台中我得到的是:{ filter: { helped: 'true' }, sort: { dateAdded: '-1' } },并且 helpedsort 变成了字符串。

当我将 { helped: 'true' } 传递给 mongo.find() 时,没有返回任何结果,因为在MongoDB中我存储的是布尔值。

在查询解析后,如何在后端获得正确的变量类型?

英文:

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?

答案1

得分: 1

布尔值在发送到Mongo之前就已经变成了字符串。HTTP是一种基于文本的协议,无论您将其作为GET参数发送到URL中的内容都是字符串,由服务器负责将其转换为适当的数据类型。

请参阅https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript以获取有关如何执行适合您用例的转换的灵感。

英文:

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 https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript for inspiration how to do the conversion suitable to your usecase.

答案2

得分: 0

起初,我想使用一个NPM包来自动转换所有接收到的JSON,以避免将来对后端代码的任何关注。但显然我没有耐心进一步研究这个问题。所以我制定了临时解决方案:

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

请注意,我只翻译了代码部分,没有包括您的问题或其他内容。

英文:

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

huangapple
  • 本文由 发表于 2023年7月24日 19:23:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76753981.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定