云功能/Firestore.当字段停留在不同的文档中时如何触发 [英] Cloud functions/Firestore. How to trigger when the fields stay in different documents

查看:97
本文介绍了云功能/Firestore.当字段停留在不同的文档中时如何触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

As pictured above, I have two documents in my device-configs collection. The first: device-configs/garagem. Which I'll call document_1. And the second: device-configs/garagem2. Which I'll call document_2.

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

Whenever the field garagestate (document_2) is false, the value of the field (type map) value.openPercent of document_1 must be 100. Whenever the field garagestate (document_2) is true, the value of the field value.openPercent of document_1 must be 0 Explaining: There is a possibility within the project of the value of document_2 to be changed manually in other Client project. So I need this cloud functions 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

推荐答案

每个云函数都应该返回一个 Promise 或一个值.在您的情况下,您应该返回从数据库中获取值的 Promise,然后更新另一个文档.

Every Cloud Function should return a Promise or a value. In your case, you should return the Promise which gets the value from the database, and then subsequently updates the other document.

此外,您不应该嵌套 Promise.推荐使用Promise Chaining.

Also, you should not nest Promises. It is recommended to use Promise Chaining.

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

UPDATE: I have added the code after adding Promise chaining and returning the promise in the cloud function. mapOf is also not required as you can update the object directly.

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 });
                        }
                    }
                })
    
        });

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

You can also add checks for whether the document exists or not if that's not guaranteed.

这篇关于云功能/Firestore.当字段停留在不同的文档中时如何触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆