在我的集合中,有一个文档可以接收三个字段,但我只需要根据通知的值保留两个字段,例如,我有字段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);
注意:按照您的代码当前的结构,它对您创建的每个记录执行2次写入调用,一次是在实际创建记录时,然后是我建议的更新调用。这可能会给您的系统带来一些开销,或者至少增加您的写入操作数量,这可能会对计费产生重大影响,我建议您不要在云功能中执行此检查,而是在前端执行。