Cloud Functions example - Updating firestore documents

Hi all,

I've been struggling for a while to get a cloud function working and didn't find many posts for inspiration. I've finally got it working so thought I'd share in case it comes in handy for someone later.

OBJECTIVE

My app stores the user's display_name in posts as well as in the user collection. This is somewhat redundant and means that if the user changes their display_name I need to update all the user's posts.

I've created a cloud function that is triggered by user display_name update. It queries the posts collection and updates the display_name field for all posts by the user.

CLOUD FUNCTION

Here's the code:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
// To avoid deployment errors, do not call admin.initializeApp() in your code

exports.updateNameInPosts = functions.region('australia-southeast1').
	runWith({
		memory: '128MB'
  }).https.onCall(
  async (data, context) => {
		const newDisplayName = data.newDisplayName;
		const user = data.user;
    // Write your code below!

    // Note that this is a 1st Gen function so syntax different

    console.log('new name is:', newDisplayName);    

    const fullUserRef = '/users/' + user;
    console.log('fullUserRef is:', fullUserRef); 

    const db = admin.firestore();
    const userDocRef = db.doc(fullUserRef);
    const promises = [];  

    const postsCollection = db.collection("posts");
    console.log('step 1');    
    const snapshot = await postsCollection.where('userref','==',userDocRef).get()
    console.log('got snapshot');    
    snapshot.forEach(doc => {
      const docref = doc.ref;
      promises.push(
        docref.update({
        display_name: newDisplayName
        })
      );
      console.log('got a doc');    
    })
    await Promise.all(promises);
    console.log('finished');    

    // Write your code above!
  }
);

Here's how it's configured in FF

I hope this is helpful for someone

17
1 reply