Google cloud firestore 用于删除字段并向其他字段添加前缀的触发器

Google cloud firestore 用于删除字段并向其他字段添加前缀的触发器,google-cloud-firestore,google-cloud-functions,Google Cloud Firestore,Google Cloud Functions,在我的集合中,有一个文档可以接收三个字段,但根据通知的值,我只需要保留两个字段,例如,我有字段a、B和C,根据不同的值,我不需要记录字段B或C。我还需要在字段A中写入前缀。我遵循这一点,创建了一个可以读取字段的函数,但无法更改或删除它们。我使用了onCreate事件 请参见我的示例: const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initialize

在我的集合中,有一个文档可以接收三个字段,但根据通知的值,我只需要保留两个字段,例如,我有字段a、B和C,根据不同的值,我不需要记录字段B或C。我还需要在字段A中写入前缀。我遵循这一点,创建了一个可以读取字段的函数,但无法更改或删除它们。我使用了onCreate事件

请参见我的示例:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.testFields =
  functions.firestore.document('documentos/{documentoId}/ocorrencias/{ocorrenciaId}').onCreate(async (snapshot, context) => {
    const ocorrencia = snapshot.data();
    //I can read the values
    fieldA = ocorrencia.fieldA;
    console.log('Field A: ', fieldA); //'Teste'
    fieldB = ocorrencia.fieldB;
    console.log('Field B: ', fieldB); //5
    fieldC = ocorrencia.fieldC;
    console.log('Field C: ', fieldC); //6
    if(fieldB > FieldC){
      //the C field does not need to be recorded
      prefix = 'B';

    }else{
      //the B field does not need to be recorded
      prefix = 'C';
    }
    //now I need to record the prefix next to FieldA
    //my FieldA should look like this: 'CTeste'
  });

你可以这样做:

if (fieldB > FieldC) {
    //the C field does not need to be recorded
    prefix = 'B';
    ocorrencia.fieldC = null;
} else {
    //the B field does not need to be recorded
    prefix = 'C';
    ocorrencia.fieldb = null;
}
//now I need to record the prefix next to FieldA
//my FieldA should look like this: 'CTeste'
ocorrencia.fieldA = prefix + fieldA;
functions.firestore.collection('ocorrencias').update(ocorrencia);

注意:按照代码当前的结构,它对您创建的每个记录执行两个写调用,一个是对记录的实际创建,然后是我建议的更新调用。这可能会给您的系统带来一些开销,或者至少会增加写入操作的数量,这对计费来说可能非常重要,我建议您不要在云功能中执行此检查,而是在前端执行此检查。

您好,Deivis,欢迎使用堆栈溢出,你能编辑这篇文章并添加一些代码,这样社区就可以检查你迄今为止所做的尝试吗?@DeivisÁtila,提供的解决方案是否解决了你所面临的问题?