You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复遍历对象数组通过Mongoose插入MongoDB时的TypeError错误

错误原因

你代码里有三个核心问题导致报错:

  1. forEach回调的参数i是数组中的元素对象本身,不是索引,你用leagues[i]访问相当于用对象当索引去读取数组,肯定返回undefined,调用.title自然抛出TypeError
  2. forEach不支持异步等待,内部的await seedLeague.save()不会按预期顺序执行,且seedDB函数不会等所有保存操作完成就会进入后续的then逻辑
  3. 最后关闭数据库连接时mongoose.connection.close是方法,你漏了括号,不会实际执行关闭操作;另外lat、lon字段你用模板字符串转成了字符串,和模型定义的Number类型不匹配,可能触发类型错误

修复后的完整代码

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() => {
    // 改用for of循环支持异步等待
    for (const leagueItem of leagues) {
        const seedLeague = new League({
            // 直接用当前遍历到的元素对象取值,不需要再从leagues数组二次读取
            title : leagueItem.title,
            location : leagueItem.location,
            city: leagueItem.city, 
            // 不要转字符串,保持Number类型和模型匹配
            lat: leagueItem.lat,
            lon: leagueItem.lon
        })
        await seedLeague.save();
    }
}

seedDB().then( ()=>{
    // 调用close方法,加括号
    mongoose.connection.close();
})

优化建议

如果不需要对每条数据做单独处理,可以直接用insertMany批量插入,性能更好:

const seedDB =  async() => {
    await League.insertMany(leagues);
}

内容的提问来源于stack exchange,提问作者Zizo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:45:08