从 Firestore 中的数组中删除对象

Bri*_*ogg 6 arrays firebase google-cloud-functions google-cloud-firestore

我刚刚开始接触 Firebase,到目前为止确实在深入研究,但在使用云函数从集合中的数组中删除项目时遇到了一些问题。在我正在使用的应用程序中,用户在用户集合中有一个文档,其中包含不适合身份验证模型的特定于用户的数据。数据如下:

用户集合结构的屏幕截图。

(这是一个与健身相关的应用程序,因此该数组被称为“锻炼”)

用户可以创建锻炼,创建锻炼后,云函数会监视新锻炼,将新创建的锻炼的 ID 添加到用户文档中,并使用 arrayUnion 将其附加到锻炼数组中:

exports.addWorkoutToAuthorsListOfWorkouts = functions.firestore
    .document('workouts/{workoutId}')
    .onCreate((snap, context) => {
      const id = context.params.workoutId
      const name = snap.data().title
      const uid = snap.data().author

      const workout_reference = { id: id, name: name, uid: uid }
      const workoutsRef = admin.firestore().collection("users").doc(uid)

      return workoutsRef.update({
        workouts: admin.firestore.FieldValue.arrayUnion(workout_reference)
      })
    })
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我希望用户能够删除锻炼,并且我没有将字符串添加到锻炼数组中,而是添加一个如下所示的对象:

{ id: "1214", name: "My workout", uid: "123asd" }
Run Code Online (Sandbox Code Playgroud)

现在,对于这个确切的用例,我可以删除 ReactJS 应用程序中的数组,然后进行更新,但我将添加用户“喜欢”其他用户的锻炼的功能,这将导致提及将锻炼添加到其个人用户文档中的“锻炼”中。因此,如果我作为锻炼的创建者删除我的锻炼,我需要能够从拥有它的任何用户的锻炼数组中删除它。使用 arrayRemove 不起作用,因为(我假设)我无法传递要删除的对象。

执行此操作的最佳实践方法是什么?我做了这样的尝试:

exports.removeWorkoutFromAuthorsListOfWorkouts = functions.firestore
  .document('workouts/{workoutId}')
  .onDelete((snap, context) => {

    const id =  context.params.workoutId
    const uid = snap.data().author
    const name = snap.data().name
    let newWorkouts = new Array()

    admin.firestore().collection("users").doc(uid).collection("workouts").get().then((querySnapshot) => {
      querySnapshot.forEach((doc: any) => {
          if (doc.id !== id) {
            newWorkouts.push(doc.data())
          }
      });
    });

    const workoutsRef = admin.firestore().collection("users").doc(uid)

    return workoutsRef.update({
      workouts: newWorkouts
    })
  })
Run Code Online (Sandbox Code Playgroud)

但 Firebase 根本不喜欢它,而且我对这个平台还很陌生,我意识到这很可能是由于知识差距造成的,而不是 Firestore 或 Cloud Functions 的任何问题。

非常感谢您提供的任何帮助。干杯!

更新:使用以下代码使其正常工作:

exports.removeWorkoutFromSubscribersListOfWorkouts = functions.firestore
  .document('workouts/{workoutId}')
  .onDelete((snap, context) => {
    const workoutId =  context.params.workoutId
    const subscribers = snap.data().subscribers
    let newWorkouts = new Array()

    subscribers.forEach(subscriber => {
      let userRef = admin.firestore().collection("users").doc(subscriber)

      return userRef.get().then(doc => {
        return userRef.update({
          workouts: doc.data().workouts.filter(workout => workout.id !== workoutId)
        })
      })
    })
    .catch(() => {
      console.log("error")
    })
  })
Run Code Online (Sandbox Code Playgroud)