Search code examples
javascriptnode.jsmongoosefetch

I want to save a data from api to mongodb compass by mongoose?


am trying to save a data from fetch api to my database using mongoose so the data never come. could anyone help? and thank you, this is my code

`

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


`

i tried to search about the problem in google and i did not find anything similar.


Solution

  • Instead of writing such a complicated for loop, you can just use the .insertMany() method on the model

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

    the following is a complete working snippet

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

    this inserted 114 documents

    PS: you just need to install node-fetch and mongoose