无法过滤 JSON 之类的东西

Can't filter JSON-like thing

我正在 node.js 中使用来自 https://swapi.co/ 的数据编写应用程序。我的一项功能需要检查指定的行星是否存在于我的数据库中,如果不存在,api 应该从 swapi 下载行星的数据,但不知何故我无法检索有关名称行星指定的数据,我只能获取格式为 link 的数据:https://swapi.co/api/planets/?format=json

方法代码:

router.route('/Planets')
    .post(function (req, res) {
        var planet = new Planet(req.body);
        //validate planet.name here
        Planet.find({name: planet.name}, function (err, planet) {
            if (err) {
                res.status(500).send(err);
            }
            if (planet == '') {
                console.log("action: planet not found");
                request.get(
                    'https://swapi.co/api/planets/?format=json',
                    {json: true},
                    function (error, response, body) {
                        console.log(body);
                    }
                );
                // planet.save();
                res.status(201).send(planet);
            } else {
                res.status(201).send(planet);
            }
        })
    })
    .get(function (req, res) {
        Planet.find(function (err, planets) {
            if (err) {
                res.status(500).send(err);
            } else {
                res.json(planets);
            }
        });
    });

这是JSON。 行星存储在 results 中。 所以结果是对象数组,现在您可以使用 forin.

遍历数组的所有元素

您可以随心所欲地操作,循环、过滤器等

fetch("https://swapi.co/api/planets/?format=json")
  .then(res => res.json())
  .then(res => {
    console.log(res);
    // Array of planets stored in res.results
    for (let i=0; i<res.results.length; i++) {
      console.log("Name:", res.results[i].name, "Data:", res.results[i])
    }
  });