Home > Blockchain >  How put JSON data to MongoDB?
How put JSON data to MongoDB?

Time:03-01

Im beginner on mongo & javascript, i made a approximate code may be to push all API JSON response on my collection db, so i should take the lead with this code to do something that looks like something rather than doing nothing :

The goal of this file is convert to a card all result of JSON api response, but before that i need to store this response

import { defineStore } from "pinia";
import axios from "axios";
import { MongoClient } from 'mongodb'

export const useCardStore = defineStore("cardStore", {
 state: () => ({
  cards: [], 
  }),
  getters:{
     allCards: (state) => state.cards
  },
 actions: {
   async loadCards() {
   try {
    const response = await axios.get("https://api.adzuna.com/....");
    this.cards = response;
    const { data } = response;
    response.data.results.forEach((item) => {
      console.log(item);
      return item.get().then(response => {
        JSON.parse(response.body.text());
        var MongoClient = require('mongodb').MongoClient;
        var url = 'mongodb://localhost:27017/MyCollection';

        MongoClient.connect(url, function(db) {
        
        var myDB = db.db("JobSeeker");
        
        var myobj = [item];
        
          myDB.collection("cardsJobs").insertMany(myobj, function(res) {
          console.log("Number of item inserted: "   res.insertedCount);
          db.close();
        });
      })
     });
    });
  } 
  catch (error) {
    console.log(error);
      }
  },
 },
});

CodePudding user response:

//modify your code like this
var url = "API CALL HERE"

request(url, function(error, response, body){

 if(!error && response.statusCode == 200){
    var data = JSON.parse(body);
    res.send(data);

    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/mydb";

    MongoClient.connect(url, function(err, db) {
      if (err) throw err;
      var myobj = [];
      myobj.push(data);
      db.collection("dabas").insertMany(myobj, function(err, res) {
        if (err) throw err;
        console.log("Number of documents inserted: "   res.insertedCount);
        db.close();
      });
    });
 }
});

//your problem is you passing obj not array
//see below link for your reference

https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/

  • Related