【问题标题】:Angular Firestore - search for and update single documentAngular Firestore - 搜索和更新单个文档
【发布时间】:2019-10-05 17:37:46
【问题描述】:

我是网络新手(一切都是异步的)。我正在尝试在 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
  });

在执行另一个命令之前如何等待一个订阅返回?你嵌套订阅吗?有什么我不知道的非常基本的东西吗?

谢谢。

【问题讨论】:

    标签: javascript google-cloud-firestore angularfire2


    【解决方案1】:

    我不认为 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 应该做什么(因为它是一个身份操作,提供与其输入相同的结果),但以防万一这对您很重要。

    【讨论】:

    • 我试过这个方法,代码:this.firestore.collection('robots', ref =&gt; ref.where('name', '==', fight.winner)) .get() .then(... ,但得到错误Property 'then' does not exist on type 'Observable&lt;QuerySnapshot&gt;'.
    • 您仍在使用 AngularFire,而我的回答显示了如何直接在 JavaScript SDK 上执行此操作。删除 this.firestore.collection('robots', ref =&gt; 位,因为它不需要,在这里没有帮助。
    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 2018-09-15
    • 2018-04-21
    • 1970-01-01
    • 2019-10-23
    相关资源
    最近更新 更多