Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
Looping over array with nested objects

I am trying to loop over an array of nested object to seed my mongodb. I was able to achieve using the following for loop, but the issue with this one is that it picks a random object from the array.

const seedDB =  async() => {
    for (let i = 0; i < 4; i++) {
        const which = Math.floor(Math.random() * 5);
        const seedLeague =  new League({
            title : `${leagues[which].title}`,
            location : `${leagues[which].location}`,
            city: `${leagues[which].city}`, 
            lat: `${leagues[which].lat}`,
            lon: `${leagues[which].lon}`
        })
        await seedLeague.save();
    }
 }

What I actually want is to loop of the array and add each object in the array. I tried to achieve that using a forEach and for (element of array), but both are giving a typeError.



const seedDB =  async() => {
    await League.deleteMany({});
    leagues.forEach( async (i)=>{
        new League({
            title : `${leagues[i].title}`,
            location : `${leagues[i].location}`,
            city: `${leagues[i].city}`, 
            lat: `${leagues[i].lat}`,
            lon: `${leagues[i].lon}`
        })
        await League.save();
    })
}

const seedDB =  async() => {
    await League.deleteMany({});
    for (let aLeague of leagues) {
        new League({
            title : `${leagues[aLeague].title}`,
            location : `${leagues[aLeague].location}`,
            city: `${leagues[aLeague].city}`, 
            lat: `${leagues[aLeague].lat}`,
            lon: `${leagues[aLeague].lon}`
        })
        await League.save();
    }

Could someone please help and fix the issue with above forEach and for .. of ..?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In the second two you are calling .save() on the League class instead of on an instance of that class. In the first one you are assigning each new instance to a const (seedLeague) and calling save on that.

The second two options should both work, you just need to create a const inside each iteration of the loop and call save on that new object:

const seedDB =  async() => {
   await League.deleteMany({});
   leagues.forEach( async (i)=>{
       const seedLeague = new League({
           title : `${leagues[i].title}`,
           location : `${leagues[i].location}`,
           city: `${leagues[i].city}`, 
           lat: `${leagues[i].lat}`,
           lon: `${leagues[i].lon}`
       })
       await seedLeague.save();
   })
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda