How to store nested fetched JSON api in NodeJS, using mongodb

Viewed 14

please help me out, I have fetched an api which give me nested json, now when I want to store that data in mongodb, I am able to establish connection and database also get created but no data is getting saved in database, can someone help me in this.

JSON file is like this:

{ "india": {"curr" : "rupee","code": "91","ca": "New Delhi"},"Usa":{"curr" : "American dollar","code": "1","ca":"Washington dc"},}}

Like this there more entries, around 100+,

I have fetched this api, with https in NodeJS. I don't know how to store these in my database, I have done creating model for mongodb using mongoose, at the last step when I want to pass the fetched URL data, I am unable to create document

Below is code I using:

const express = require("express")
const https = require("https") 
const mongoose = require("mongoose") 
const app = express() 
mongoose.connect("mongodb://0.0.0.0:27017/try") 
app.get("/", function(req, res){

const countrySchema =new mongoose.Schema({ 

world:{ country: String, 
code: Number,
capital: String 
}}) 
const Earth = mongoose.model("Earth", countrySchema) 
const url = "fetched api"
https.get(url,(res) => {
    let body = "";

    res.on("data", (chunk) => {
        body += chunk;
    });

    res.on("end", () => {
        try {
            let json = JSON.parse(body);
           
            const planet = new Earth({
                country:json
            })
        } catch (error) {
            console.error(error.message);
        };
    });

}).on("error", (error) => {
    console.error(error.message);

    

})

0 Answers
Related