用嵌套对象循环遍历数组



我试图循环在嵌套对象的数组种子我的mongodb。我能够使用下面的for循环实现,但是这个循环的问题是它从数组中选择一个随机对象。

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

我实际想要的是循环数组并添加数组中的每个对象。我试图实现使用forEach和for(数组的元素),但两者都给出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();
}

有人可以帮助解决上述forEach和for ..的问题吗?. . ?

在第二个示例中,您在League类而不是该类的实例上调用.save()。在第一个例子中,你将每个新实例分配给const (seedLeague)并调用save。

后两个选项应该都能工作,你只需要在循环的每次迭代中创建一个const,并对新对象调用save:

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

相关内容

  • 没有找到相关文章

最新更新