使用带条件的 Firebase 批量写入批量更新(使用 WHERE 函数)
Bulk Update using Batched Write of Firebase with conditions (using WHERE function)
我的系统的主要目标是在经过身份验证的用户更改或重命名他或她的帐户名称时更新 post 在我的论坛上发帖的用户的名称。
整个过程没有错误,但不幸的是,在论坛中 post 发帖的其他用户也更新了他们的名字。
所以这是输出:
我尝试以下操作:
- 我使用 Firebase 中的 WHERE 函数来过滤用户(登录用户本身)所做的 post。我不知道为什么整个过程都失败了。
这是代码片段。
async updateAll(username) {
const batch = this.afs.firestore.batch();
// cUser is the USER ID
const userRef = this.afs
.collection('post', (ref) => ref.where('postedById', '==', this.cUser))
.ref.get();
(await userRef).forEach((element) => {
batch.update(element.ref, {
postedBy: username,
});
});
return batch.commit();
}
您以 .ref.get()
结束查询。那里的 .ref
实际上是 returns 您 运行 查询的集合,因此您最终加载了整个 post
集合。
您需要 subscribe to snapshotChanges
,或者只使用常规 JavaScript SDK 来完成此操作(因为您没有直接访问 UI,我通常会发现更容易):
const userRef = firebase.firestore()
.collection('post').where('postedById', '==', this.cUser).get();
(await userRef).forEach((element) => {
batch.update(element.ref, {
postedBy: username,
});
});
我的系统的主要目标是在经过身份验证的用户更改或重命名他或她的帐户名称时更新 post 在我的论坛上发帖的用户的名称。
整个过程没有错误,但不幸的是,在论坛中 post 发帖的其他用户也更新了他们的名字。
所以这是输出:
我尝试以下操作:
- 我使用 Firebase 中的 WHERE 函数来过滤用户(登录用户本身)所做的 post。我不知道为什么整个过程都失败了。
这是代码片段。
async updateAll(username) {
const batch = this.afs.firestore.batch();
// cUser is the USER ID
const userRef = this.afs
.collection('post', (ref) => ref.where('postedById', '==', this.cUser))
.ref.get();
(await userRef).forEach((element) => {
batch.update(element.ref, {
postedBy: username,
});
});
return batch.commit();
}
您以 .ref.get()
结束查询。那里的 .ref
实际上是 returns 您 运行 查询的集合,因此您最终加载了整个 post
集合。
您需要 subscribe to snapshotChanges
,或者只使用常规 JavaScript SDK 来完成此操作(因为您没有直接访问 UI,我通常会发现更容易):
const userRef = firebase.firestore()
.collection('post').where('postedById', '==', this.cUser).get();
(await userRef).forEach((element) => {
batch.update(element.ref, {
postedBy: username,
});
});