API Request passing ID fetched from mongodb

Viewed 20

I´m a Java Dev so I need help from NodeJS guys!

Task: create a script that retrieves '_id', 'document', and 'corporateName' from MongoDB, then take the retrieved '_id', and pass it as a parameter to an API request. The last part should be taking 'document', 'corporateName' + 'client_id', 'client_secret' and export it into a single csv file.

It might be a very simple script! Therefore I´ve done this till now:

const {MongoClient} = require('mongodb');
const uri = "mongodb+srv://<privateInfo>/";
const client = new MongoClient(uri);

async function run() {
try {
 const database = client.db("merchant-profile");
 const ecs = database.collection("merchant_wallet");
 const api = `https://<prodAPI>/v1/merchant/wallet/${id}/oauth2`;
 const ecOpt = {_id: 1, document: 1, corporateName: 1};
 const credOpt = {client_id: 1, client_secret: 1};
 const ec = ecs.find({}).project(ecOpt);
 let id = ec.forEach(id => cred._id);
 const cred = api.find({}).project(credOpt);

 await cred.forEach(console.dir);
} finally {
 await client.close();
}
}
run().catch(console.dir);

I´m trying to understand how can I take '_id' fetched in 'ec' and pass it as a param to the 'cred' call. This would already be awesome! If you could help me out with the CSV issue as well it would be perfect. So I don´t want just the answer, but understand how to do this.

Thank you all in advance!

1 Answers

This is the way I found to do it:

const { default: axios } = require("axios");
const { MongoClient } = require("mongodb");

const uri = "mongodb+srv://admin:sLKJdsdRp4LrsVtLsnkR@pp-core-prd.fy3aq.mongodb.net/";
const client = new MongoClient(uri);

async function run() {
  try {
    const database =  client.db("merchant-profile");
    const ecs =  database.collection("merchant_wallet");
    const data = [];
    await ecs.find({}).forEach(async function teste(response) {
      const id = response._id;
      const api = `https://api.pedepronto.com.br/v1/merchant/wallet/${id}/oauth2`;

      try{
        const res = await axios.get(api);
        data.push({client_secret: res.data[0].client_secret, client_id: res.data[0].client_id})
      }catch(e){
        console.log(e);
      }
    })
} finally {

    await client.close();

}

}

run().catch(console.dir);

It iterates over the find method and appends the fetched id to the uri.

Related