Firestore中重复的文档可以通过云功能在文档编辑时更新吗?

时间:2020-04-12 13:36:54

标签: typescript firebase google-cloud-firestore google-cloud-functions

我设置了以下Firestore:

  • 用户/ uid /关注/ followingPersonUid /
  • 用户/ uid /关注者/ followerPersonUid /

因此,如果用户A将跟随用户B,则用户A将被添加到用户B的followers子集合中,用户B也将被添加到用户A的后续子集合中

但是,假设用户A更新了他的个人资料信息(姓名,照片,用户名等)。然后,他的用户文档将在他的文档中更改,但是无论他是其他用户(如用户B或E&F)的关注者子集合中的关注者,都需要在任何地方进行更改。

这可以通过云功能来完成吗? 我已经为云函数创建了一个onCreate()触发器,但是该函数不知道他是其追随者的其他用户列表(uid),因此我无法在需要的地方应用此更改。

这是我在Firebase CLI中的函数,这是一个Firestore .onUpdate()触发器。我已经评论了卡住的地方

export const onUserDocUpdate = functions.region('asia- 
east2').firestore.document
('Users/{userId}').onUpdate((change, context) => {
const upDatedUserData = change.after.data()

const newName = upDatedUserData?.name
const profilePhotoChosen = upDatedUserData?.profilePhotoChosen
const updatersUserId = upDatedUserData?.uid
const newUserName = upDatedUserData?.userName

//This is where I am stuck, I have the updated document info but how do
//I find the other documents at firestore that needs updation with this 
//updated information of the user
    return admin.firestore()
    .collection('Users').doc('{followeeUserId}')
    .collection('Followers').doc(updatersUserId)
    .set({
    name: newName, 
    userName: newUserName,
    profilePhotoChosen: profilePhotoChosen,
    uid: updatersUserId
  })

})

我应该改为使用可调用函数,其中客户端可以发送以下需要更新的用户ID的列表。

1 个答案:

答案 0 :(得分:1)

据我了解,用户会更新其个人资料,然后您还希望在其所有关注者数据中更新该个人资料。由于您同时保留了关注者和关注者,因此您应该能够读取触发了云功能的用户的子集合:

export const onUserDocUpdate = functions.region('asia- 
east2').firestore.document
('Users/{userId}').onUpdate((change, context) => {
  const upDatedUserData = change.after.data()

  const newName = upDatedUserData?.name
  const profilePhotoChosen = upDatedUserData?.profilePhotoChosen
  const updatersUserId = upDatedUserData?.uid
  const newUserName = upDatedUserData?.userName

  const userDoc = change.after.ref.parent; // the user doc that triggered the function
  const followerColl = userDoc.collection("Followers");

  return followerColl.get().then((querySnapshot) => {
    const promises = querySnapshot.documents.map((doc) => {
      const followerUID = doc.id;
      return admin.firestore()
        .collection('Users').doc(followerUID)
        .collection('Followees').doc(updatersUserId)
        .set({
          name: newName, 
          userName: newUserName,
          profilePhotoChosen: profilePhotoChosen,
          uid: updatersUserId
        })
    });
    return Promise.all(promises);
  });
})

可能是我那里有一些拼写错误/语法错误,但是语义应该很扎实。我不确定的最大事情是您维护的跟随者/跟随者逻辑,因此我使用了集合名称,因为它们对我来说最有意义,可以与您的相反。