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



我是网络新手(以及异步的所有内容(。我正在尝试在 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
});

在执行另一个命令之前,如何等待一个订阅返回?你嵌套订阅吗?有没有一些我只是还不知道的真的很基本的东西?

谢谢。

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

最新更新