Issue
I have these collections.
I need get a field value from "Protocolos finalizados" and put in a console.log().
Can someone help me, please?
I´m using node.js and typescript.
Below in my code I try to compare the value of fields from different collections and get a result that came from "Protocolos finalizados" and "Listagem de pagamento" collections.
import * as functions from 'firebase-functions'
import { google } from 'googleapis'
import { initializeApp } from 'firebase-admin/app'
const serviceAccount = require('../sheets_updater_service_account.json')
const sheets = google.sheets('v4')
import { getFirestore } from "firebase-admin/firestore"
initializeApp()
const firestore = getFirestore()
module.exports.readAndUpdateAdministrativeSheet = functions.https.onRequest(async (request, response) => {
// =========================== AUTENTICAÇÃO FIREBASE ===================================
const jwtClient = new google.auth.JWT({
email: serviceAccount.client_email,
key: serviceAccount.private_key,
scopes: ['https://www.googleapis.com/auth/spreadsheets']
})
await jwtClient.authorize()
// ================= CONEXÃO COM A PLANILHA CRIAÇÃO DE FILTROS =========================
const { data } = await sheets.spreadsheets.values.get({
auth: jwtClient,
spreadsheetId: 'google sheets id XXXXXXXXXXXXXXXXXXXXXX',
//range: `Listagem de pagamento!A2:X6`,
})
// ========= CRIAÇÃO DE BANCO DE DADOS DA COLEÇÃO LISTAGEM DE PAGAMENTO ================
const generateDuplicities = data.values!.map(async row => {
const [nome, cpf, numeroRequerimento, arbitramentoHonorários] = row
firestore.collection("Listagem de pagamento").doc(numeroRequerimento).set({
nome, cpf, numeroRequerimento, arbitramentoHonorários
})
// =========================== DUPLICIDADE ADMINISTRATIVA ===================================
const duplicitiesWithAdministrativeCharges = new Array()
const resultduplicitiesWithAdministrativeCharges = firestore.collection('Protocolos finalizados') //1lGPC1UuxVRplJCVfAXAPWeigjgx1ETyx1OpdtCCJoXo (Pagamentos finalizados)
.where("autosPF", "==", arbitramentoHonorários) // autosPF => Planilha Pagamentos finalizados / arbitramentoHonorários => Planilha de Criaão de filtros
.where("cpf_PF", "==", cpf) // cpf_PF => Planilha Pagamentos finalizados / cpf => Planilha de Criação de filtros
//const requerimento = firestore.collection('Protocolos finalizados').doc().collection('requerimento')
const mesPagamento = firestore.collection('Protocolos finalizados').doc("mesPagamento")
const resDuplicitiesWithAdministrativeCharges = await resultduplicitiesWithAdministrativeCharges.get()
if (resDuplicitiesWithAdministrativeCharges.size) {
resDuplicitiesWithAdministrativeCharges.forEach(doc => {
if (resDuplicitiesWithAdministrativeCharges.size == 1) {
functions.logger.log("Foi encontrada " + `${resDuplicitiesWithAdministrativeCharges.size} ` + "duplicidade administrativa referente a pessoa " + `${nome}.`)
functions.logger.log(doc.id)
functions.logger.log(doc.id,'mesPagamento')
functions.logger.log(doc.data()) //NÃO MEXER
//functions.logger.log("Criação de filtros (Listagem de pagamento): " + `${'arbitramentoHonorários'}: ${arbitramentoHonorários}`, `${'nome'}: ${nome}`, "\nPagamentos finalizados (Protocolos finalizados): " + `${'requerimento'}: ${requerimento}`, `${'mesPagamento'}: ${mesPagamento}`)
// Requerimento e mesPagamento devem vir da planilha de pagamentos finalizados
duplicitiesWithAdministrativeCharges.push(`${'arbitramentoHonorários'}: ${arbitramentoHonorários}`, `${'nome'}: ${nome}`, `${'requerimento'}: ${doc.id}`, `${'mesPagamento'}: ${mesPagamento}`)
functions.logger.log(duplicitiesWithAdministrativeCharges)
} else if (resDuplicitiesWithAdministrativeCharges.size > 1) {
functions.logger.log("Foram encontradas " + `${resDuplicitiesWithAdministrativeCharges.size} ` + "duplicidades administrativa referente a pessoa " + `${nome}.`)
functions.logger.log(doc.id)
//functions.logger.log("Criação de filtros (Listagem de pagamento): " + `${'arbitramentoHonorários'}: ${arbitramentoHonorários}`, `${'nome'}: ${nome}`, "\nPagamentos finalizados (Protocolos finalizados): " + `${'requerimento'}: ${requerimento}`, `${'mesPagamento'}: ${mesPagamento}`)
// Requerimento e mesPagamento devem vir da planilha de pagamentos finalizados
duplicitiesWithAdministrativeCharges.push(`${'arbitramentoHonorários'}: ${arbitramentoHonorários}`, `${'nome'}: ${nome}`, `${'requerimento'}: ${doc.id}`, `${'mesPagamento'}: ${mesPagamento}`)
functions.logger.log(duplicitiesWithAdministrativeCharges)
} else if (resDuplicitiesWithAdministrativeCharges.size === 0) {
functions.logger.log('Não há duplicidades administrativas nesta lista')
console.log('Não há duplicidades administrativas nesta lista')
}
})
}
})
await Promise.all(generateDuplicities)
})
exports.protocolosFinalizados = functions.https.onRequest(async (request, response) => {
const jwtClient = new google.auth.JWT({
email: serviceAccount.client_email,
key: serviceAccount.private_key,
scopes: ['https://www.googleapis.com/auth/spreadsheets']
})
await jwtClient.authorize()
const { data } = await sheets.spreadsheets.values.get({
auth: jwtClient,
spreadsheetId: 'google sheets id XXXXXXXXXXXXXXXXXXXXXX',
//range: `Protocolos finalizados!A406480:L406482`
})
data.values?.forEach(row => {
const [requerimento, autosPF, cpf_PF, mesPagamento] = row
firestore.collection("Protocolos finalizados").doc(requerimento).set({
requerimento, autosPF, cpf_PF, mesPagamento
})
})
})
Solution
I tried and replicated your Firebase data structure,
and you will be able to get a field value from your collection using this query:
import * as functions from 'firebase-functions';
import { initializeApp } from "firebase/app";
import { getFirestore, collection, query, getDocs, onSnapshot } from "firebase/firestore";
const firebaseApp = initializeApp({
projectId: "PROJECT_ID"
});
const db = getFirestore();
var ref = query(collection(db, "test-data"));
const querySnapshot = await getDocs(ref);
querySnapshot.forEach((doc) => {
console.log("mesPagamento: ", doc.data().mesPagamento);
});
And the output will be:
mesPagamento: 11/2019
mesPagamento: 12/2020
For more information, you may refer on Get data with Cloud Firestore. It's a good way to start learning Firestore queries. There's also a guide on how to perform simple and compound queries in Firestore.
Answered By - RJC
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.