【问题标题】:Unable to fill mongodb document with external api data无法用外部 api 数据填充 mongodb 文档
【发布时间】:2022-06-10 22:36:52
【问题描述】:

我正在尝试用来自 unsplash 和 randomuser api 的数据填充我的 mongodb 文档。

  const userdata = await axios.get("https://randomuser.me/api/?results=51");
  const imagedat = await axios.get(
    "https://api.unsplash.com/photos/random/?count=51&client_id=GWDzPpjHk743C2QnVBRxu8PtmOI3npF5sePZZ7o0pg4"
  ); 

我为 51 个结果调用两个 api,但在 22 个结果后,catch 下的代码被显示,并且只创建了 22 个文档 如何存储所有 51 个结果

const seeddata = async () => {
  const userdata = await axios.get("https://randomuser.me/api/?results=51");
  const imagedat = await axios.get(
    "https://api.unsplash.com/photos/random/?count=51&client_id=GWDzPpjHk743C2QnVBRxu8PtmOI3npF5sePZZ7o0pg4"
  );
  try {
    await MemoModel.deleteMany({});
    const userarr = await userdata.data;
    const imagedata = await imagedat.data;

    for (let i = 0; i < 50; i++) {
      const data = new MemoModel({
        name: {
          firstname: `${userarr.results[i].name.first}`,
          lastname: `${userarr.results[i].name.last}`,
          username: `${userarr.results[i].login.username}`,
        },
        about: {
          user: `${userarr.results[i].gender} aged ${userarr.results[i].dob.age}. Rotting here for ${userarr.results[i].registered.age} `,
        },
        location: {
          country: `${
            countryarr[Math.floor(Math.random() * countryarr.length)]
          }`,
          state: `${userarr.results[i].location.state}`,
          city: `${userarr.results[i].location.city}`,
          address: `${userarr.results[i].location.street.name} ,${userarr.results[i].location.street.number}`,
          zipcode: userarr.results[i].location.postcode,
        },
        email: {
          user: `${userarr.results[i].email}`,
        },
        image: {
          dp: `${userarr.results[i].picture.large}`,
          coverimage: "https://source.unsplash.com/random/?mountains",
        },
        posts: {
          postno: i,
          posttitle: `${imagedata[i].description}`,
          postcontent: `${imagedata[i].urls.regular}`,
          postlikesno: imagedata[i].likes,
          postcommentno: imagedata[i].width,
        },
      });
      await data.save();
    }
  } catch {
    console.log("catastrophic Failure");
  }
};
seeddata().then(() => {
  mongoose.connection.close();
});

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    您可以在捕获后添加 (err) 并对其进行控制台而不是“灾难性错误”吗?我会告诉我们破坏你的代码的整个错误:

        catch (err) {
          console.error(err)
       }
    

    【讨论】:

      猜你喜欢
      • 2021-06-13
      • 2018-06-13
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      相关资源
      最近更新 更多