在这种情况下如何查询和过滤数据?

罗德里戈·菲亚德·帕西尼

此功能旨在创建图像中的数据库。

exports.processosjudiciais = functions.https.onRequest(async (request, response): Promise<any> => {

    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: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        range: `Processos judiciais!A11664:E11667`
    })
    
    const updatePromises = new Array()
    data.values?.forEach(row => {
        const [processoBE, autoresBE, documentosDosautores, arbitramentoDeHonoráriosBE, valorDaCausa] = row
        firestore.collection("Processos judiciais").doc(processoBE).set({
            processoBE, autoresBE, documentosDosautores, valorDaCausa
        })
        arbitramentoDeHonoráriosBE.split("; ").forEach((v: string) => {
            updatePromises.push(
                firestore.collection("Processos judiciais").doc(processoBE).collection('fee-arbitrations - Base de Execução').doc(v).set({
                    arbitramentoDeHonoráriosBE: v,
                    processoBE,
                })
            )
        })
    })
    return await Promise.all(updatePromises)
})

在此处输入图像描述

在此处输入图像描述

我需要将我用红色箭头突出显示的数据与谷歌电子表格中的值(我也在图像中以红色突出显示)进行比较。我该如何进行这种比较?从我制作的代码中,如果我只与第一个“where”进行比较,我可以提取结果。我需要与两个“哪里”进行比较。我究竟做错了什么?为什么我不能做这个比较?

在此处输入图像描述

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: '1bGJGQInmGmI-ODHM5hSZtQdvbPFVzWT70oPD6mTxcmU',
        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 [idade, nome, cpf, cpf_x, numeroRequerimento, arbitramentoHonorários,
            valorArbitrado, valorDeferido, valorComplementar, status, resultado, codigoBanco,
            banco, agencia, conta, dataDoRequerimento, dataRequerimento, dataStatus,
            comarca, vara, ato, assistidos, email, telefone] = row
        firestore.collection("Listagem de pagamento").doc(numeroRequerimento).set({
            idade, nome, cpf, cpf_x, numeroRequerimento, arbitramentoHonorários,
            valorArbitrado, valorDeferido, valorComplementar, status, resultado, codigoBanco,
            banco, agencia, conta, dataDoRequerimento, dataRequerimento, dataStatus, comarca, vara, ato,
            assistidos, email, telefone
        })
const duplicitiesWithJudicialCharges = new Array()
        const resultduplicitiesWithJudicialCharges = firestore.collection("Processos judiciais") //1VgkQFGZCKvINMLtnVLIeC0tQhAjxeNk92PQN5QKLq-Q (Base de dados de execuções)
            .where("arbitramentoDeHonoráriosBE", "array-contains", arbitramentoHonorários) // Arbitramento de Honorários => Planilha Base de dados de execuções  /  Arbitramento de Honorários => Planilha de Criação de filtros
            .where("documentosDosautores", "==", cpf) // documentosDosautores => Planilha Base de dados de execuções  /  cpf => Planilha de Criação de filtros
        const resDuplicitiesWithJudicialCharges = await resultduplicitiesWithJudicialCharges.get()        
        if (resDuplicitiesWithJudicialCharges.size) {
            resDuplicitiesWithJudicialCharges.forEach(doc => {
                if (resDuplicitiesWithJudicialCharges.size == 1) {
                    functions.logger.log("Foi encontrada " + `${resDuplicitiesWithJudicialCharges.size} ` + "duplicidade judicial referente a pessoa " + `${nome}.`)
                    functions.logger.log(doc.id) // NÃO MEXER
                    functions.logger.log(doc.data()) //NÃO MEXER
                    
                    duplicitiesWithJudicialCharges.push(`${'arbitramentoHonorários'}: ${arbitramentoHonorários}`, `${'nome'}: ${nome}`, `${'processoBE'}: ${doc.data().processoBE}`)
                    functions.logger.log(duplicitiesWithJudicialCharges)//NÃO MEXER
                } else if (resDuplicitiesWithJudicialCharges.size > 1) {
                    functions.logger.log("Foram encontradas " + `${resDuplicitiesWithJudicialCharges.size} ` + "duplicidades Judicial referente a pessoa " + `${nome}.`)
                }
            })
        }    
        else if (resDuplicitiesWithJudicialCharges.size <= 0){
            functions.logger.log('Não há duplicidades judicial nesta lista')
        }
 })
    await Promise.all(generateDuplicities)
})

在此处输入图像描述

谁能告诉我我做错了什么?

马克·安东尼 B

在这行代码上:

const resultduplicitiesWithJudicialCharges = firestore.collection("Processos judiciais") //1VgkQFGZCKvINMLtnVLIeC0tQhAjxeNk92PQN5QKLq-Q (Base de dados de execuções)
.where("arbitramentoDeHonoráriosBE", "array-contains", arbitramentoHonorários) // Arbitramento de Honorários => Planilha Base de dados de execuções  /  Arbitramento de Honorários => Planilha de Criação de filtros
.where("documentosDosautores", "==", cpf) 

有一些问题我想指出。

  1. 您的 Firestore 数据结构有一个嵌套集合,这意味着您在基于给定图像的文档中有一个父集合和一个子集合:在此处输入图像描述
  2. 您只查询Processos judiciais集合内的文档,因此您的查询无法到达子集合内的文档。
  3. array-contains只能在显示的图像中类型为. 的字段中使用arraystring
  4. 如果变量arbitramentoHonoráriosarray,则应改用in运算符。如果是,string那么您应该使用==运算符。
  5. 上面给定代码的唯一有效查询是这个:.where("documentosDosautores", "==", cpf)

为了能够查询集合和子集合,必须先查询集合并循环所有匹配的数据,然后调用另一个查询来查询文档的子集合并将其推送到初始化的数组中。请参见下面的代码:

const resultduplicitiesWithJudicialCharges = db.collection('Processos judiciais').where('documentosDosautores', '==', cpf);
const duplicitiesWithJudicialCharges = [];

resultduplicitiesWithJudicialCharges.get().then((querySnapshot) => {
  // Loop through all the matched result from the parent collection query.
  querySnapshot.forEach((parentDoc) => {
    // Logs documents from the parent collection.
    console.log(childDoc.id, " => ", doc.data());
    // Queries the subcollection where in `parentDoc.ref` are the documents from the result of 1st query.
    parentDoc.ref.collection(<'YOUR-SUBCOLLECTION-NAME'>).where('arbitramentoDeHonoráriosBE', '==', arbitramentoHonorários).get().then((querySnapshot) => {
      // Loop through all matched result from the subcollection query for each document matched from the parent query.
      querySnapshot.forEach((childDoc) => {
          // Logs documents from the subcollection.
          console.log(childDoc.id, " => ", doc.data());
          // Push data to the initialized array. Also used the `parentDoc.data()` that we fetched on the previous query.
          duplicitiesWithJudicialCharges.push(`${'arbitramentoHonorários'}: ${arbitramentoHonorários}`, `${'nome'}: ${nome}`, `${'processoBE'}: ${parentDoc.data().processoBE}`)
      });
    });
  });
});

在上面的代码片段上添加了一些注释以获得更好的解释。


有关更多相关信息,您可以查看以下文档:

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

django在这种情况下如何使用Q和过滤related_name?

在这种情况下,如何编写SQL查询?

在这种情况下如何正确查询?

在这种情况下,如何在MYSQL / SQL中查询数据?

在这种情况下数据绑定如何工作

在这种情况下如何更新sql数据?

在这种情况下如何访问特定的JSON数据?

在这种情况下,如何设置setInterval()和removeInterval()?

在这种情况下如何使用“和”“如果”

在这种情况下如何撰写

这是在这种情况下PHP的开关盒或数据库查询速度之间

在这种情况下如何制作Q对象表达式(按ForeignKey字段过滤)?

django:在这种情况下如何使用过滤器选项?

闪亮:在这种情况下如何为条件过滤器制作反应输入?

在这种情况下,我将如何建立sql查询?

在这种情况下,如何查询两个表?

在这种情况下,如何使MYSQL选择查询一对多?

在这种情况下如何进行动态查询。sql 2005

||之间的差异 和|| =在这种情况下

在这种情况下,如何使用Laravel存储多个数据?

在这种情况下如何创建数据库表?

在这种情况下,如何通过匹配公共值来生成新的数据帧?

在这种情况下如何在asp.net中访问数据库?

Python-在这种情况下如何解释将数据分配给数组

在这种情况下,Python pandas 数据框合并如何工作?

SQL Server如何在这种困难的情况下利用数据透视

在这种情况下,如何在tidyverse中将数据管道传输到stat_function()?

在这种情况下如何使数据库保持一致?

在这种情况下,如何将数据从html传输到php