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

求助:使用Mongoose将API数据存入MongoDB Compass失败

问题排查与修复

核心问题分析

  1. 数据库连接未校验:原代码未处理MongoDB连接的成功/失败状态,可能数据库根本未建立连接,导致数据无法写入。
  2. Ayahs数组处理错误:API返回的surahs[i].ayahs是数组类型,原代码直接访问数组的number等属性,会得到undefined,无法正确存入子文档。
  3. 保存操作无错误反馈:handleError函数未定义,且使用回调式保存无法捕获错误,也未等待保存完成,导致出错无提示。
  4. Fetch未处理HTTP错误:Fetch仅在网络故障时抛出错误,HTTP状态码错误(如404、500)不会自动抛出,可能获取到无效数据。

修复后的完整代码

Mongoose模型与连接部分

const mongoose = require('mongoose');

// 异步处理数据库连接,确保连接成功后再执行数据写入
async function connectDB() {
  try {
    await mongoose.connect('mongodb://localhost:27017/Quran');
    console.log('MongoDB连接成功');
  } catch (err) {
    console.error('MongoDB连接失败:', err);
    process.exit(1); // 连接失败时退出进程
  }
}

const SurahSchema = mongoose.Schema({
  ayahs: [{
    number: Number,
    numberInSurah: Number,
    text: String
  }],
  englishName: String,
  englishNameTranslation: String,
  name: String,
  number: Number,
  revelationType: String,
});

const Surah = mongoose.model('Surah', SurahSchema);

module.exports = { connectDB, Surah };

数据获取与写入部分

const { connectDB, Surah } = require('./your-model-file-path'); // 替换为你的模型文件路径
const API = 'http://api.alquran.cloud/v1/quran/quran-uthmani';

async function getdata() {
  try {
    // 先确保数据库连接成功
    await connectDB();

    const res = await fetch(API);
    // 处理HTTP错误
    if (!res.ok) {
      throw new Error(`HTTP错误: ${res.status}`);
    }
    const data = await res.json();

    // 遍历每个章节
    for (const surahItem of data.data.surahs) {
      // 正确处理ayahs数组:遍历每个ayah提取字段
      const ayahs = surahItem.ayahs.map(ayah => ({
        number: ayah.number,
        numberInSurah: ayah.numberInSurah,
        text: ayah.text
      }));

      const newSurah = new Surah({
        ayahs,
        englishName: surahItem.englishName,
        englishNameTranslation: surahItem.englishNameTranslation,
        name: surahItem.name,
        number: surahItem.number,
        revelationType: surahItem.revelationType
      });

      // 等待保存完成,捕获错误
      await newSurah.save();
      console.log(`章节 ${surahItem.number} 保存成功`);
    }

    console.log('所有数据保存完成');
    process.exit(0);
  } catch (err) {
    console.error('数据处理失败:', err);
    process.exit(1);
  }
}

getdata();

额外优化建议

  • 批量写入:如果章节数量较多,使用Surah.insertMany()替代循环单个save,提升性能。
  • 数据去重:添加唯一索引(如number字段),避免重复写入相同数据。
  • 环境变量:将数据库连接字符串存入环境变量,避免硬编码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:00:50