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

102
Visualizações
Loop over a nested array of objects

I am trying to load the following array with 2 object in the below league model.

The array that I want to load:

module.exports = [
    {
        title: "Osdorp StraatVoetbal",
        location: "Osdorp",
        city: "Amsterdam",
        lat: 52.3599,
        lon: 4.7891,
    },
    {
       title: "Slotervaart StraatVoetbal",
       location: "Slotervaart",
       city: "Amsterdam",
       lat: 52.3562,
       lon: 4.8273,
    }
];

The League model:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const LeagueSchema = new Schema ({
    title: String,
    location: String,
    city: String,
    lat: Number,
    lon: Number
});

module.exports = mongoose.model('League', LeagueSchema);

I am using the following function to load the array, but getting TypeError.

const mongoose = require('mongoose');
const League = require('../models/league');
const leagues = require('./leagues');

mongoose.connect('mongodb://localhost:27017/footballeagues', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});

const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', ()=>{
    console.log("Mongoose Database connected")
});

const seedDB =  async() => {
    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();
    })
}

seedDB().then( ()=>{
    mongoose.connection.close;
    //console.log('connection closed')
})

Could someone please help and advise me how to fix the below error:

enter image description here

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

0

The issue is that your code expects an array index as the parameter to your forEach() callback, but what it actually receives is the array value.

Here is working code that will solve your issue:

    const seedDB =  async() => {
        leagues.forEach( async (element)=>{
            const seedLeague = new League({
                title : `${element.title}`,
                location : `${element.location}`,
                city: `${element.city}`, 
                lat: `${element.lat}`,
                lon: `${element.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