值可能会更改的 Firebase 文档参考

Firebase Document reference where value may change

我有一个集合,其中包含显示用户个人资料图片的信息,该用户图片取自另一个集合(用户)的文档。我的问题是我在创建新文档时向图片添加了 link,这意味着如果将来用户更改个人资料图片,另一个集合将不会有该新信息。有什么办法可以用 firebase 解决这个问题吗?

每当用户集合中的信息更新时,我想从另一个集合中获取数据。

集合中需要实时数据的文档值

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

/users 集合中的文档值

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

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

Mises 提到,一种标准方法是使用 Firestore Cloud Function,它是 triggered when the user document changes

以下代码可以解决问题。我假设其他集合的文档使用与用户文档相同的 ID。

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

    });