Angular Firestore - 搜索和更新单个文档

Angular Firestore - search for and update single document

我是网络新手(所有内容都是异步的)。我正在尝试在 Angular + Firebase 应用程序中完成两步过程:

  1. 查询 Firestore 集合以查找与过滤器匹配的文档 ID(名称 == 'theName')。
  2. 使用 ID 然后更新文档。

我来自嵌入式世界,在那里我可以做这样的事情(应用程序的上下文 - 我正在尝试跟踪战斗机器人竞赛的结果)。

// Update the winning robot's doc with results

// Find the ID of the robot we're looking for (ex. winningRobotName = "Some Name")
this.firestore.collection('robots', ref => ref.where('name', '==', winningRobotName)).snapshotChanges()
  .subscribe(data => {
    this.bots = data.map(e => {
      return {
        id: e.payload.doc.id,
        name: e.payload.doc.data()['name'],
        // other fields
      } as Robot;
   })
});

let robot = this.bots[0];  <--------- This doesn't work because I reach here before the above call returns.

// Update this robot with new fields
this.firestore.doc('robots/' + robot.id)
  .update({
    fightCount : robot.fightCount + 1,
    winCount : robot.winCount + 1,
    // other updates
  });

如何在执行另一条命令之前等待对 return 的订阅?您嵌套订阅吗?有什么我还不知道的非常基本的东西吗?

谢谢。

我不认为 AngularFire 可以帮助您,而是直接在常规 JavaScript SDK 上执行此操作:

ref.where('name', '==', winningRobotName))
   .get()
   .then((snapshots) => {
     snapshots.forEach((doc) => 
       doc.ref.update({
         id: doc.id,
         name: doc.data().name
       })
   })
})

我不太确定 name: doc.data().name 应该做什么(因为它是一个身份操作,提供与其输入相同的结果),但以防万一这对你很重要。