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 ..?
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();
})
}