Reputation: 19
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:
Upvotes: 0
Views: 57
Reputation: 167
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();
})
}
Upvotes: 1