Barrufet
Barrufet

Reputation: 692

Update document in cloud function from an Application

I'm trying to call a cloud function from my app to update some document, but something isn't working.

I don't think the problem is on my app code, probably is something in my node.js of cloud function.

Code from app

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()

Path doesn't matter because in my cloud function I'm hardcoding it.

Cloud Function in 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;
    });

So it's not updating and I want cloud function to manage operations like changing a document.

Question: Am I doing something wrong? Should I check for something?

Upvotes: 1

Views: 176

Answers (2)

Barrufet
Barrufet

Reputation: 692

Thank you very much for your help guys, after testing a lot of stuff with my node.js newbie code I made it work and understood what was wrong.

I started watching videos on cloud functions and noticed that they were using the firebase-admin import:

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

And now looks like it access correctly to the database and updates the document. Thank you very much!

Upvotes: 1

Soumendra Mishra
Soumendra Mishra

Reputation: 3663

You can grant "allUsers" with "Cloud Functions Invoker" role in Cloud Function:

enter image description here

Upvotes: 2

Related Questions