从应用程序更新云功能中的文档

时间:2020-09-05 11:34:28

标签: android google-cloud-firestore google-cloud-functions

我正在尝试从我的应用程序中调用云函数来更新某些文档,但某些功能无法正常工作。

我不认为问题出在我的应用程序代码上,可能是我的云功能的node.js中的问题。

应用中的代码

val functions = FirebaseFunctions.getInstance()
val db = FirebaseFirestore.getInstance()

val dataHashMap = hashMapOf(
    "db" to db
)
functions
    .getHttpsCallable("changeDocument")
    .call(dataHashMap)
    .continueWith {
        if(it.isSuccessful){
            Log.i("ChangeDocument", "Success")
        }else{
            Log.i("ChangeDocument", "Not success")
        }

    }.await()

路径无关紧要,因为在我的云函数中,我正在对其进行硬编码。

node.js中的云功能

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

exports.changeDocument = functions
    .https.onCall(async(data, context) => {

        const db = data.db;

        const postCollectionRef = db.collection('usernames');
        const postDocumentRef = postCollectionRef.doc('8bahgPCa9sgcdmGkDkUQSwjT7F22');

        await postDocumentRef.update({ username: 'documentChanged' });
        return true;
    });

所以它没有更新,我希望云功能可以管理诸如更改文档之类的操作。

问题:我做错什么了吗?我应该检查点东西吗?

2 个答案:

答案 0 :(得分:2)

您可以在Cloud Function中为“ allUsers ”授予“ Cloud Functions Invoker ”角色:

enter image description here

答案 1 :(得分:0)

非常感谢您的帮助人员,在用我的node.js新手代码测试了很多内容之后,我使它工作并了解了什么地方。

我开始在云功能上观看视频,并注意到它们正在使用firebase-admin导入:

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

exports.changeDocument = functions
    .https.onCall(async(data, context) => {

        const postCollectionRef = admin.firestore().collection('usernames');
        const postDocumentRef = postCollectionRef.doc('8bahgPCa9sgcdmGkDkUQSwjT7F22');
        
        return await postDocumentRef.update({
            username: `documentChanged`
        });
    });

现在看起来它可以正确访问数据库并更新文档。非常感谢!