Mike_Baltimore
Mike_Baltimore

Reputation: 21

Scheduled Cloud Function Doesn't Return a Value due To Undefined "uid"

I am writing this post because I am facing some issues with my scheduled cloud function.

Step 1: Access the following / collection: users => doc: uid => collection: bank => doc: account.

Step 2: Increase my users' (all of them) dailyRewardCounter by 150 every 24h.

The thing is that my function can't access my users' collection uid and return an error because the scheduled function is not able to read the uid (cf. picture).

Question: Do you know how can I access each users' subcollection based on their individual 'uid' to add 150 in the collection 'bank' ?

enter image description here

 export const dailyCreditReinitialize = functions.pubsub.schedule('0 0 * * *').onRun(async (context) => {
    const uid = context.auth!.uid; // seems like the function does not read that 
    const userRef = db.collection('users').doc(uid);
    const userSnap = await userRef.get();
    const getUid = userSnap.data()!.uid;
    const bankCollectionRef = db.collection('users').doc(getUid).collection('bank');

        return bankCollectionRef.get()
        .then(querySnapshot =>{
            if (querySnapshot.empty){
                console.log("Nothing to return")
                return null;
            } else {
                let batch = db.batch();
                querySnapshot.forEach(doc => {
                    batch.update(doc.ref, {
                        dailyRewardCounter: 150,
                    });
                });
                return batch.commit();
            }
        })
        .catch(error => {
            console.log(error);
            return null;
        });
    })

Upvotes: 1

Views: 48

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83181

Contrary to a Realtime Database triggered Cloud Function, with a scheduled Cloud Function, context.auth is null.

If I correctly understand your question ("Increase my users' (all of them)") you need to loop over all the users documents of the Collection. Something along the following lines in pseudo-code:

  1. Loop on the users Collection and get all the users IDs
  2. For each user, get the querySnapshot of the bankcollection
  3. Loop on each of the querySnapshots to update the bank doc

Upvotes: 1

Related Questions