sei-ec-remote / project-2-issues

1 stars 0 forks source link

can't push newly created pokemons in teams' pokemons arrays #309

Closed AlexMcBex closed 1 year ago

AlexMcBex commented 1 year ago

What's the problem you're trying to solve?

when I try to add a pokemon in a team a new instance of pokemon gets created but not pushed in the pokemons array of the team

Post any code you think might be relevant (one fenced block per file)

//POST - update team with new pokemon
router.get('/:teamid/addPokemon/:pkmnname', async (req, res)=> {
    const pokemonName = req.params.pkmnname
    const pokemonInfo = await axios(`${process.env.POKEAPI_URL}/pokemon/${pokemonName}`)
    const pokemonData = pokemonInfo.data
    const teamId = req.params.teamid
    req.body.owner = req.session.userId
    req.body.name = pokemonName
    req.body.type1 = pokemonData.types[0].type.name
    req.body.type2 = " "
    // req.body.type2 = pokemonData.types[1].type.name
    req.body.sprite = pokemonData.sprites.front_default
    const newPokemon = req.body
    Pokemon.create(newPokemon) 
    .then(pokemon =>{
        Team.findById(teamId)
        .then(team =>{
            team.pokemons.push(pokemon)
        })
        res.redirect(`/pokemon/${pokemon.id}`) 
    }
    )
    .catch(err =>{
        res.redirect(`/error?error=${err}`)
        })
})

If you see an error message, post it here. If you don't, what unexpected behavior are you seeing?

if I try to console log the pokemons team array it's empty

What is your best guess as to the source of the problem?

probably using the wrong logic

What things have you already tried to solve the problem?

trying to change the order of promises or using different terminology

Paste a link to your repository here

https://github.com/AlexMcBex/PokemonTeams_Project-2/tree/version1

asands94 commented 1 year ago

After you push make sure you save the object using .save()

timmshinbone commented 1 year ago

in here, add a line that returns the saved team then add another .then and place your res.redirect in there:

.then(team =>{
     team.pokemons.push(pokemon)
     return team.save()
})
.then(team => {
  //redirect goes here instead
}
AlexMcBex commented 1 year ago

It worked! now when I log the team I only see the ids. How can I see the values of the objects instead? should I use .populate()?

[
  {
    _id: new ObjectId("63d2ae03b5ad5899e43a2d04"),
    name: 'Kanto',
    description: 'Kanto Pokemons only',
    pokemons: [
      new ObjectId("63d2d8d014b6b017d8c56204"),
      new ObjectId("63d2d8f414b6b017d8c56210")
    ],
    owner: new ObjectId("63cfff7b17cb5f39a09ef501"),
    createdAt: 2023-01-26T16:44:51.472Z,
    updatedAt: 2023-01-26T19:48:04.393Z,
    __v: 2
  }
]
timmshinbone commented 1 year ago

Yep! Populate is how you do that, but think about where you need to see them, and put your populate in the right spot!

AlexMcBex commented 1 year ago

It works! thank you guys! closing the issue