简体   繁体   English

如何使用 Firebase 云功能更新 Firestore 文档的值

[英]How to update value of a firestore document with a firebase cloud functions

I have firestore database and I would like to trigger a cloud functions when there is a change in a field of a firestore document.我有 firestore 数据库,我想在 firestore 文档的字段发生更改时触发云功能。 I would like the cloud function to look at what has changed and use the new data to update another filed of the firestore document.我希望云功能查看发生了什么变化,并使用新数据更新 firestore 文档的另一个文件。

Example例子

Lets assume the document in the picture has changed and has the new values as in the picture below让我们假设图片中的文档已更改并具有如下图所示的新值

在此处输入图片说明

Now I would like to update the value of accuracy to successes / attempts , ie I would like accuracy to be 6/11 = 0.54现在我想将accuracy的值更新为successes / attempts ,即我希望准确度为 6/11 = 0.54

What should I write in the function?我应该在函数中写什么? Here is what I have so far这是我到目前为止所拥有的

exports.calculateAccuracy = functions.firestore.document('/users/{userId}/wordScores')
    .onUpdate((change, context) => {

      //what to write here?

    });

Extra question: how many reads/writes I am going to consume to update the accuracy?额外的问题:我将消耗多少读/写来更新准确性?

Thanks!!!谢谢!!!

The following should do the trick.以下应该可以解决问题。 Notice the path in the Cloud Firestore trigger ( users/{userId}/wordScores/{scoreDocId} ): it points to a Document, not to a Collection.请注意 Cloud Firestore 触发器中的路径 ( users/{userId}/wordScores/{scoreDocId} ):它指向文档,而不是集合。 More info in the documentation . 文档中的更多信息。

exports.calculateAccuracy = functions.firestore
    .document('users/{userId}/wordScores/{scoreDocId}')
    .onUpdate((change, context) => {

        const newValue = change.after.data();
        const previousValue = change.before.data();

        if ((newValue.attempts !== previousValue.attempts) || (newValue.successes !== previousValue.successes)) {
            return change.after.ref.update({
                accuracy: newValue.successes / newValue.attempts
            });

        } else {
            return null;
        }

    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM