我想通过mongoose将API中的数据保存到mongodb compass中?

8ehkhllq  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(128)

我试图保存一个数据从获取API到我的数据库使用 Mongoose 所以数据从来没有来。有人可以帮助吗?谢谢你,这是我的代码
`

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/Quran')

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

var surah = mongoose.model('Surah',SurahSchema)

字符串

const API = 'http://api.alquran.cloud/v1/quran/quran-uthmani'
async function getdata(){
    const res = await fetch(API)
    const data = await res.json()
    for (let i = 0; i < data.data.surahs.length; i++) {
      const Surah =  new surah({
        ayahs:[{
            number:data.data.surahs[i]['ayahs'].number,
            numberInSurah:data.data.surahs[i]['ayahs'].numberInSurah,
            text:data.data.surahs[i]['ayahs'].text
        }],
        englishName:data.data.surahs[i]['englishName'],
        englishNameTranslation:data.data.surahs[i]['englishNameTranslation'],
        name:data.data.surahs[i]['name'],
        number:data.data.surahs[i]['number'],
        revelationType:data.data.surahs[i]['revelationType']
       })
       
       Surah.save(function (err) {
        if (err) return handleError(err);
        // saved!
      });   
    }
}   
 
getdata()


`
我试着在谷歌上搜索这个问题,没有找到类似的东西。

lh80um4z

lh80um4z1#

您可以直接在模型上使用.insertMany()方法,而不是编写如此复杂的for循环

const API = 'http://api.alquran.cloud/v1/quran/quran-uthmani'

async function getdata(){
    const res = await fetch(API);
    const data = await res.json();
    try{
        const inserted = await surah.insertMany(data.data.surahs); 
    }catch(e){
        console.log("Some error");
        console.log(e);
    }
}   
 
getdata()

字符串
下面是一个完整的工作片段

import mongoose from 'mongoose';
import fetch from 'node-fetch';

mongoose.connect('mongodb://localhost:27017/Quran');

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

const API = 'http://api.alquran.cloud/v1/quran/quran-uthmani';

async function getdata() {
  const res = await fetch(API);
  const data = await res.json();
  try {
    const inserted = await surah.insertMany(data.data.surahs);
    console.log(inserted);
    process.exit(0);
  } catch (e) {
    console.log('Some error');
    console.log(e);
    process.exit(0);
  }
}

getdata();


这114个文件
PS:你只需要安装node-fetch和mongoose

相关问题