Import JSON Database to Firestore

Asked

Viewed 28 times

-1

I have 2 databases in json where one is of indications, and the other are the comments of these statements. Follow the model of each database (with a single data):

indication:

{
   "id_indicacao": 52,
   "boo_ativo": 1,
   "categoria": "Alimentação",
   "sub_categoria": "Cafés e Comidinhas",
   "dt_registro": "2016-03-07 13:30:34",
   "txt_email": "[email protected]",
   "id_cliente": 45,
   "id_usuario": 2678,
   "nome": "Robataria - Temaki & Robata",
   "criador_indicacao": "FRANCISMAR RANGEL DE SOUZA",
   "txt_unidade": "17 Bloco 1",
   "site": "",
   "telefone": "(11) 99389-1773"
 }

comments on the alert:

{
   "id_indicacao": 52,
   "boo_ativo": 1,
   "categoria": "Alimentação",
   "sub_categoria": "Cafés e Comidinhas",
   "dt_registro": "2016-03-07 13:30:34",
   "id_cliente": 45,
   "id_usuario": 2678,
   "nome": "Robataria - Temaki & Robata",
   "criador_indicacao": "FRANCISMAR RANGEL DE SOUZA",
   "txt_unidade": "17 Bloco 1",
   "email": "[email protected]",
   "site": "",
   "telefone": "(11) 99389-1773"
 },

I need that once the indication is imported, my script do a search in the comment base and add each comment within its respective indication.

To do this I tried to follow the model of the article: https://medium.com/lucas-moyer/how-to-import-json-data-into-firestore-2b370486b622#:~:text=To%20add%20this%20data%20to,Almost%20done!

My final script was as follows:

const firebase = require('firebase');

require('firebase/firebase-firestore');

firebase.initializeApp({MINHAS_CREDENCIAIS});

let indicacoes = [{
   "id_indicacao": 52,
   "boo_ativo": 1,
   "categoria": "Alimentação",
   "sub_categoria": "Cafés e Comidinhas",
   "dt_registro": "2016-03-07 13:30:34",
   "txt_email": "[email protected]",
   "id_cliente": 45,
   "id_usuario": 2678,
   "nome": "Robataria - Temaki & Robata",
   "criador_indicacao": "FRANCISMAR RANGEL DE SOUZA",
   "txt_unidade": "17 Bloco 1",
   "site": "",
   "telefone": "(11) 99389-1773"
 },
 ...
];

let comentarios =[{
   "id_indicacao": 52,
   "boo_ativo": 1,
   "categoria": "Alimentação",
   "sub_categoria": "Cafés e Comidinhas",
   "dt_registro": "2016-03-07 13:30:34",
   "id_cliente": 45,
   "id_usuario": 2678,
   "nome": "Robataria - Temaki & Robata",
   "criador_indicacao": "FRANCISMAR RANGEL DE SOUZA",
   "txt_unidade": "17 Bloco 1",
   "email": "[email protected]",
   "site": "",
   "telefone": "(11) 99389-1773"
 },
 ...
];

 indicacoes.forEach( obj => {
   let valorindicacao = obj.id_indicacao;
   firebase.firestore().collection('teste').add({      
      ativo: obj.boo_ativo,
      categoria: obj.categoria,
      sub_categoria: obj.sub_categoria ? obj.categoria : "outros",
      dt_registro: new Date(obj.dt_registro),
      email: obj.txt_email,
      id_cliente: obj.id_cliente.toString(),
      id_usuario: obj.id_usuario.toString(),
      nome: obj.nome,
      criador_indicacao: obj.criador_indicacao,
      txt_unidade: obj.txt_unidade,
      site: obj.site ? obj.site : "Sem site",
      txt_telefone: obj.txt_telefone ? obj.txt_telefone : "sem telefone", 
   }).then( doc => {
     let indicacao = doc.id;
     console.log('documento inserido: ', doc.id);
     comentario.forEach( async comentario => {
       if (comentario.id_avaliacao == valorindicacao) {
         await firebase.firestore().collection('teste').doc(doc.id).collection('comentarios').add({
          ativo: comentario.boo_ativo,
          avaliacao: comentario.nr_avaliacao,
          comentario: comentario.txt_comentario,
          criador_comentario: comentario.nome_autor,
          dt_registro: new Date(comentario.dt_registro),
          id_cliente: comentario.id_cliente,
          id_usuario: comentario.id_usuario,
         }).then( resultcomentario => {
           console.log('incluido com sucesso')
         }).catch(erro => {
           console.log(erro);
         })
       }
     })
   }).catch( error => {
     console.log('occorreu um erro: ', error);
   })
 });

As you can see, I tried using Promise’s answer on . then() to capture the id the firestore generated(doc id.), and right after searching the comment base looking for comments that have the same id_indication of the newly entered indication; if you find it should enter in the path of doc id., open a collection "comments" and insert the comment inside. It turns out that for some reason he’s not responding in the expected way - I believe because of asynchrony problems or the size of the database.

How do I import all this data?

2 answers

0

I managed to find a solution. Really foreach was not respecting the iteration of my script. so I created two functions that keep my iteration contained, and call it at the end of my script.

Follows the code:

const firebase = require('firebase');

require('firebase/firebase-firestore');

firebase.initializeApp({MINHAS_CREDENCIAIS});

//Aqui declaro as funções enviar_comentarios e enviar_indicações:

let enviar_comentarios = (comentarios, valorIndicacao, doc) => {
  for(ivalue of comentarios){
    if(ivalue.id_indicacao == valorIndicacao){
      firebase.firestore().collection('database').doc(ivalue.id_cliente.toString()).collection('indicacao').doc(doc.id).collection('comentarios').add({
        ativo: ivalue.boo_ativo,
        avaliacao: ivalue.nr_avaliacao,
        comentario: ivalue.txt_comentario,
        criador_comentario: ivalue.nome_autor,
        dt_registro: new Date(ivalue.dt_registro),
        id_cliente: ivalue.id_cliente,
        id_usuario: ivalue.id_usuario,    
      }).then(() => {
        console.log('coisou')
      })
    }
  }
}

let enviar_indicacoes = (indicacoes) => {
  for(ivalue of indicacoes){
    let valorIndicacao = ivalue.id_indicacao;
      firebase.firestore().collection('database').doc(ivalue.id_cliente.toString()).collection('indicacao').add({
      ativo: ivalue.boo_ativo,
      categoria: ivalue.categoria,
      sub_categoria: ivalue.sub_categoria ? ivalue.categoria : "outros",
      dt_registro: new Date(ivalue.dt_registro),
      email: ivalue.txt_email,
      id_cliente: ivalue.id_cliente.toString(),
      id_usuario: ivalue.id_usuario.toString(),
      nome: ivalue.nome,
      criador_indicacao: ivalue.criador_indicacao,
      txt_unidade: ivalue.txt_unidade,
      site: ivalue.site ? ivalue.site : "Sem site",
      txt_telefone: ivalue.txt_telefone ? ivalue.txt_telefone : "sem telefone",      
    }).then( async doc => {
      console.log('deu bom: ', doc.id);
      await enviar_comentarios(comentario, valorIndicacao, doc);
    }).catch( error =>
      console.log(error)  
    )

  }
}

//aqui declaro os dados em json dos comentarios e das indicações:
let indicacoes = [{
   "id_indicacao": 52,
   "boo_ativo": 1,
   "categoria": "Alimentação",
   "sub_categoria": "Cafés e Comidinhas",
   "dt_registro": "2016-03-07 13:30:34",
   "txt_email": "[email protected]",
   "id_cliente": 45,
   "id_usuario": 2678,
   "nome": "Robataria - Temaki & Robata",
   "criador_indicacao": "FRANCISMAR RANGEL DE SOUZA",
   "txt_unidade": "17 Bloco 1",
   "site": "",
   "telefone": "(11) 99389-1773"
 },
 ...
];

let comentarios =[{
   "id_indicacao": 52,
   "boo_ativo": 1,
   "categoria": "Alimentação",
   "sub_categoria": "Cafés e Comidinhas",
   "dt_registro": "2016-03-07 13:30:34",
   "id_cliente": 45,
   "id_usuario": 2678,
   "nome": "Robataria - Temaki & Robata",
   "criador_indicacao": "FRANCISMAR RANGEL DE SOUZA",
   "txt_unidade": "17 Bloco 1",
   "email": "[email protected]",
   "site": "",
   "telefone": "(11) 99389-1773"
 },
 ...
];

//aqui invoco a função:
enviar_indicacoes(indicacoes);

The use of "for ... of" respected the iteration and for me, the solution presented worked.

0

"I believe that due to asynchrony problems or the size of the database."

In this excerpt here is the problem of asynchrony :

 async comentario => {
   if (comentario.id_avaliacao == valorindicacao) {
     await fi .....

Sentence of the article:

" If you can only take one thing from this article, it is: async/await does not work in Array.prototype.foreach. Let’s look at an example to see why: "

Reference

Changes the forEach for another way to iterate:

async function getTodos() {
  for (const [idx, url] of urls.entries()) {
    const todo = await fetch(url);
    console.log(`Received Todo ${idx+1}:`, todo);
  }

  console.log('Finished!');
}

One more thing: comentario.id_avaliacao == valorindicacao ?

Is not id_indicacao?

  • Thanks for the strength, I will test your solution right now! "ValueIndication" is a variable that I created just to store doc.id. I found it better to indicate so than to arrive at the second foreach and write "doc.id"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.