Home > OS >  Firebase Document reference where value may change
Firebase Document reference where value may change

Time:05-06

I have a situation where I have a collection which contains information that displays a user profile picture, this user picture is taken from another collection's (users) document. My problem is that I add a link to the picture when I create the new document, this means that if in future the user changes the profile picture the other collection would not have that new information. Is there a way I can solve this with firebase?

I want to get the data from the other collection whenever the information in users collection is updated.

document value in the collection that needs live data

{profile-picture:"image-from-users-collection goes here"}

document value in /users collection

{user-picture:"my-pic.png"} 

CodePudding user response:

I want to get the data from the other collection whenever the information in users collection is updated.

A mentioned by Mises, one standard approach is to use a Firestore Cloud Function which is triggered when the user document changes.

The following code will do the trick. I make the assumption that the document of the other collection uses the same ID than the user document.

exports.updateUserImage = functions
    .firestore
    .document('users/{userId}')
    .onUpdate(async (change, context) => {

        try {

            const newValue = change.after.data();
            const previousValue = change.before.data();
            
            if (newValue['user-picture'] !== previousValue['user-picture']) {
                
                await admin.firestore().collection('otherCollection').doc(context.params.userId).update({'profile-picture':newValue['user-picture']});
                
            }
            
            return null;

        } catch (error) {
            console.log(error);
            return null;
        }

    });
  • Related