云functions/Firestore。字段停留在不同文档时如何触发

Cloud functions/Firestore. How to trigger when the fields stay in different documents

如上图,我的设备配置集合中有两个文档。第一个:device-configs/garagem。我称之为 document_1。第二个:device-configs/garagem2。我称之为 document_2.

每当字段garagestate(document_2)为false时,字段(type map) value.openPercent of document_1的值必须为100。每当字段garagestate(document_2)为真时,document_1的字段value.openPercent的值必须为0解释:有在项目中 document_2 的值可以在其他客户端项目中手动更改。所以我需要这个云函数 trigger/onUpdate.

下面我介绍我目前的代码和问题。欢迎大家的帮助:

const functions = require("firebase-functions");
const { firestore } = require("./admin");

exports.updateGarage = functions.firestore
  .document("device-configs/garagem2")
  .onUpdate((change, context) => {
    // Get an object representing the document
    // e.g. {'name': 'Marie', 'age': 66}
    const newValue = change.after.data();

    const garagestatev = newValue.garagestate;

      firestore
      .doc(`device-configs/garagem`)
      .get()
      .then((areaSnapshot) => {

        const targetDoc = areaSnapshot.data().value.openPercent

            if (garagestatev) {
                console.log("garagestate is true = targetDodc=k"+targetDoc);
      
                if (targetDoc == 100) {
                  console.log("vou mandar 0");
      
                  firestore
                    .collection("device-confings")
                    .document("garagem")
                    .update(mapOf("value.openPercent", to, 0));
                }

            } else if (!garagestatev) {
                
                console.log("garagestate is false = targetDodc=k"+targetDoc);

                if (targetDoc == 0) {
                  console.log("vou mandar 100");
                  firestore
                    .collection("device-confings")
                    .document("garagem")
                    .update(mapOf("value.openPercent", to, 100));
                }
              }
      });
  });


firebase functions:log --project control-my-lighs
2021-05-30T18:04:14.031Z ? updateGarage:     at processTicksAndRejections (internal/process/task_queues.js:97:5)
2021-05-30T18:04:15.107Z E updateGarage: Error: Process exited with code 16
    at process.<anonymous> (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:275:22)
    at process.emit (events.js:314:20)
    at process.EventEmitter.emit (domain.js:483:12)
    at process.exit (internal/process/per_thread.js:168:15)
    at Object.sendCrashResponse (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/logger.js:37:9)
    at process.<anonymous> (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:271:22)
    at process.emit (events.js:314:20)
    at process.EventEmitter.emit (domain.js:483:12)
    at processPromiseRejections (internal/process/promises.js:209:33)
    at processTicksAndRejections (internal/process/task_queues.js:98:32)
2021-05-30T18:04:25.644468172Z N updateGarage: 
2021-05-30T18:14:28.870453Z I : 
2021-05-30T18:14:29.170182Z I : 
2021-05-30T18:14:30.371944Z N updateGarage: 
2021-05-30T18:15:36.776727Z N updateGarage: 
2021-05-30T18:28:51.856151587Z D updateGarage: Function execution started
2021-05-30T18:28:51.911Z W updateGarage: Function returned undefined, expected Promise or value
2021-05-30T18:28:51.925301683Z D updateGarage: Function execution took 70 ms, finished with status: 'ok'
2021-05-30T18:32:16.601Z ? updateGarage: Unhandled rejection
2021-05-30T18:32:16.601Z ? updateGarage: TypeError: Cannot read property 'doc' of undefined
2021-05-30T18:32:16.601Z ? updateGarage:     at /workspace/index.js:20:9
2021-05-30T18:32:16.601Z ? updateGarage:     at processTicksAndRejections (internal/process/task_queues.js:97:5)
2021-05-30T18:32:17.970Z E updateGarage: Error: Process exited with code 16
    at process.<anonymous> (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:275:22)
    at process.emit (events.js:314:20)
    at process.EventEmitter.emit (domain.js:483:12)
    at process.exit (internal/process/per_thread.js:168:15)
    at Object.sendCrashResponse (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/logger.js:37:9)
    at process.<anonymous> (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/invoker.js:271:22)
    at process.emit (events.js:314:20)
    at process.EventEmitter.emit (domain.js:483:12)
    at processPromiseRejections (internal/process/promises.js:209:33)
    at processTicksAndRejections (internal/process/task_queues.js:98:32)
2021-05-30T18:41:52.632854Z I : 
2021-05-30T18:41:52.986410Z I : 
2021-05-30T18:41:54.241235Z N updateGarage: 
2021-05-30T18:43:05.140969Z N updateGarage: 
2021-05-30T19:25:19.353311Z I : 
2021-05-30T19:25:19.700197Z I : 
2021-05-30T19:25:20.976786Z N updateGarage: 
2021-05-30T19:26:25.017448Z N updateGarage: 
2021-05-30T19:28:08.685592Z I : 
2021-05-30T19:28:08.950658Z I : 
2021-05-30T19:28:10.193327Z N updateGarage: 
2021-05-30T19:29:11.637770Z N updateGarage: 
2021-05-30T19:34:04.532315Z I : 
2021-05-30T19:34:04.876667Z I : 
2021-05-30T19:34:06.052541Z N updateGarage: 
2021-05-30T19:35:13.534912Z N updateGarage: 
2021-05-30T19:35:43.595986Z I : 
2021-05-30T19:35:43.852178Z I : 
2021-05-30T19:35:45.180154Z N updateGarage: 
2021-05-30T19:36:55.044093Z N updateGarage:

https://github.com/neuberfran/updateGarage/blob/main/functions/index.js

每个 Cloud Function 都应该 return 一个 Promise 或一个值。在您的情况下,您应该 return Promise 从数据库中获取值,然后更新其他文档。

另外,你不应该嵌套 Promise。推荐使用Promise Chaining.

更新: 在添加 Promise 链接并 returning 云函数中的 promise 之后,我添加了代码。 mapOf 也不是必需的,因为您可以直接更新对象。

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
    exports.updateGarage = functions.firestore
        .document("device-configs/garagem2")
        .onUpdate((change, context) => {
    
            //Get the latest value after update
            const newValue = change.after.data();
    
            //Current state of garage
            const garagestatev = newValue.garagestate;
    
            return admin.firestore().doc(`device-configs/garagem`).get()
                .then((areaSnapshot) => areaSnapshot.data().value.openPercent)
                .then(targetDoc => {
    
                    //Target doc has openPercent of other document ('garagem')
                    if (garagestatev) {
                        console.log("garagestate is true = targetDodc=k" + targetDoc);
    
                        if (targetDoc === 100) {
                            console.log("vou mandar 0");
                            //Returning Promise inside of .then() block 
                            return admin.firestore()
                                .collection("device-configs")
                                .doc("garagem")
                                .update({ "value.openPercent": 0 });
                        }
    
                    } else {
    
                        console.log("garagestate is false = targetDodc=k" + targetDoc);
    
                        if (targetDoc === 0) {
                            console.log("vou mandar 100");
                            //Returning Promise inside of .then() block 
                            return admin.firestore()
                                .collection("device-configs")
                                .doc("garagem")
                                .update({ "value.openPercent": 100 });
                        }
                    }
                })
    
        });

如果不能保证,您还可以添加检查文档是否存在。