【问题标题】:Update document in cloud function from an Application从应用程序更新云功能中的文档
【发布时间】:2020-12-24 10:49:12
【问题描述】:

我正在尝试从我的应用中调用云函数来更新某些文档,但有些东西不起作用。

我不认为问题出在我的应用代码上,可能是我的 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;
    });

所以它没有更新,我希望云功能来管理更改文档等操作。

问题:我做错了吗?我应该检查一下吗?

【问题讨论】:

  • “但有些东西不工作”是没有足够的信息来处理。请编辑问题,以明确哪些具体情况未按您预期的方式运行,包括您正在使用的任何数据,以及表明问题所在的日志记录或错误。
  • 您的应用在哪里运行?你有什么错误?

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


【解决方案1】:

非常感谢你们的帮助,在用我的 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`
        });
    });

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 正如@guillaumeblaquiere 所说,触摸安全不是我想要的,无论如何感谢您展示我不知道的这个选项!
    猜你喜欢
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2021-01-17
    • 2021-03-27
    • 1970-01-01
    • 2020-02-08
    • 2020-02-01
    相关资源
    最近更新 更多