简体   繁体   English

当我尝试将 Object 从 api 添加到我的 mongodb atlas db NODE.JS 时,我变得不确定

[英]I get undefined when i try to add an Object from an api to my mongodb atlas db NODE JS

I get a list of pokemons from a third party API. I want to add specific ones to a favorites list when I click the add button.我从第三方 API 获得了一份宠物小精灵列表。我想在单击添加按钮时将特定的宠物小精灵添加到收藏夹列表中。 but whenever I try to render the list of favourite pokemon i just get objects saying undefined.但是每当我尝试渲染最喜欢的口袋妖怪列表时,我只会得到对象说未定义。

Any help would be appreciated.任何帮助,将不胜感激。

//Here i try to add the fetched object to my rest api//
 
function createPokemonCard(data) {
  const pokeContainer = document.getElementById("poke-container");
  const pokemonEl = document.createElement('div');
  pokemonEl.classList.add('pokemon');
  const pokeInnerHtml = `
<div class="img-container">
<img src="${data.sprites.front_default}">
</div>
<div class="pokeCard">
<h1 id="id">${data.id}</h1>
<h3 id="name">${data.name}</h3>
<h4 id="type">${data.types.map(type => type.type.name).join(", ")}</h4>
<button onclick="addFavourite()">Add</button>
</div>
`;
  pokemonEl.innerHTML = pokeInnerHtml;
  pokeContainer.appendChild(pokemonEl);
}

// i am trying to get the value//

async function addFavourite() {
  let name = document.getElementById('name').value ;
  let type = document.getElementById('type').value ;
  
  let data = {
      "name": name,
      "type": type
  }
  await fetch('https://web2-course-project-api-somrad.herokuapp.com/api/pokemons', {
      method: "POST",
      mode: 'cors',
      headers: {
          'Content-type': 'application/json; charset=utf-8'
      },
      body: JSON.stringify(data)
  });
  
}

// my back end post request//

pokemonRouter.route('/pokemons')
//POST YOUR FAVOURITE POKEMON
  .post((req, res)=>{
    const collection = db.collection("pokedex");
    collection.insertOne(req.body).then(
      () => {
        res.status(200).json({
          message: 'Added!'
        });
      }
    ).catch(
      (error) => {
        res.status(400).json({
          error: error
        });
      });
  })

this is my collection, the first three entries is added manually这是我的收藏,前三个条目是手动添加的

The list probably prints "undefined" since some of the objects provided by the database don't have a name.该列表可能会打印“未定义”,因为数据库提供的某些对象没有名称。

[
{"_id":"610d3316bf52a4e260126877","name":"Pikachu","type":"Electric"},
{"_id":"610e689defe3ad8654648ec3","name":"Charmander","type":"Fire"},
{"_id":"610e68acefe3ad8654648ec4","name":"Bulbasaur","type":"Grass"},
{"_id":"6118df7554b38705559eaacd"},
{"_id":"6118f0e493b20fefb0fd1689"},
{"_id":"6118f1e7128dd43ee68f8140"},
{"_id":"6118f2e8128dd43ee68f8141","name":"test","type":"grass"},
{"_id":"6118f57a128dd43ee68f8142"},
{"_id":"6118f5ca128dd43ee68f8143"},
{"_id":"6118f6a6128dd43ee68f8144"},
{"_id":"6118f6da128dd43ee68f8145"},
{"_id":"6118f6fd128dd43ee68f8146"},
{"_id":"6118f86f128dd43ee68f8147"},
{"_id":"6118f8e4128dd43ee68f8148"},
{"_id":"6118f924128dd43ee68f8149"},
{"_id":"6118fb34128dd43ee68f814a"}
]

This already includes my other suggestions.这已经包括我的其他建议。 渲染列表

I recommend that you filter out the invalid ones before rendering the rest.我建议您在渲染 rest 之前过滤掉无效的。


// your list with the pokemon before you create the html elements
// this simply removes all pokemon from the list that don't have a name or type
const yourList = [];
const yourFilteredList = yourList.filter(item => {

    if(item.name === undefined) return false;
    if(item.type === undefined) return false;

    return true;
})

Please also note that in mongoDB the Primary Key of the database is _id not id另请注意,在 mongoDB 中,数据库的主键是_id而不是id

<h1 id="id">${data._id}</h1>

This could also be an issue, since the type field of the API you provided is a string not a list as indicated.这也可能是一个问题,因为您提供的 API 的类型字段是一个字符串,而不是指示的列表。 This may result in an Uncaught TypeError: something.join is not a function这可能会导致Uncaught TypeError: something.join is not a function

<h4 id="type">${data.types.map(type => type.type.name).join(", ")}</h4>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在我的节点 js 应用程序中显示来自 MongoDB Atlas 的数据? - How do i display my data from MongoDB Atlas in my node js application? 当我尝试通过 node.js 从 mongodb 获取数据时出现问题? - There is some issue when I try to get data from mongodb by node.js? 为什么当我尝试访问我在 node.js 中的财产时,我变得不确定 - why I am getting undefined when I try to access on my property in node js 我在Node.JS应用程序中使用路由,当我尝试从浏览器中打开其中一个路由时,出现错误 - I use routes in my Node.JS app and when I try to open one of the routes from the browser I get an error .then在我尝试保存在MongoDB中时未定义 - .then is undefined when I try to save in MongoDB 当我尝试添加 API 密钥时,出现错误:TypeError: items.map is not a function - I get the error: TypeError: items.map is not a function, when I try to add my API key 当我尝试使用map()时,为什么我的GET响应未定义 - Why is my GET response undefined when I try to use map() Node.js和MongoDB:为什么未定义db对象? - Node.js & MongoDB: why the db object is undefined? 将Nowjs托管的Node.js服务器连接到MongoDB Atlas DB - Connecting Nowjs hosted Node.js server to MongoDB Atlas DB 如何通过node.js将数据从MongoDB传递到我的web api? - How do I pass the data from MongoDB to my web api through node.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM