Firestore:删除多个文档会尝试再次删除同一个文档
Firestore: deleting multiple documents attempts to delete the same doc again
我正在设置一项功能,根据文档中的 属性 删除多个 Firestore 文档。它确实有效,但是当它执行时,它可能会尝试删除同一个文档两次(添加了一个控制台日志语句来验证)。方法如下:
async deleteDocuments<T>(collectionName: string, fieldToCheck: string, stringValueToCheck: string) {
// Get a collection based on the field being checked and then set a property for document ID to 'id'
this._afs.collection(collectionName)
.ref.where(fieldToCheck, '==', stringValueToCheck)
.onSnapshot(async x => {
if (x) {
x.forEach(async doc => {
try {
console.log(`deleting: ${collectionName}/${doc.id}`)
await doc.ref.delete();
} catch (error) {
console.log(error)
}
})
}
})
}
虽然它不会在所有文档上重复尝试,但这确实令人困惑。例如,我有三个文档,当我 运行 这个时,它遍历了两个文档两次,一个文档一次。我在另一组有十几个左右的文档上尝试了它,看起来它有相同的结果(尽管我对 1:3 比率并不乐观)。
您正在订阅某个查询,当然,当您删除一个或多个元素时,结果会发生变化。我修复了您的代码,因此您只需删除一次订阅,而不是订阅。
async deleteDocuments<T>(collectionName: string, fieldToCheck: string, stringValueToCheck: string) {document ID to 'id'
const docs = await this._afs.collection(collectionName)
.ref.where(fieldToCheck, '==', stringValueToCheck)
.get();
docs.forEach(doc => doc.ref.delete());
}
我正在设置一项功能,根据文档中的 属性 删除多个 Firestore 文档。它确实有效,但是当它执行时,它可能会尝试删除同一个文档两次(添加了一个控制台日志语句来验证)。方法如下:
async deleteDocuments<T>(collectionName: string, fieldToCheck: string, stringValueToCheck: string) {
// Get a collection based on the field being checked and then set a property for document ID to 'id'
this._afs.collection(collectionName)
.ref.where(fieldToCheck, '==', stringValueToCheck)
.onSnapshot(async x => {
if (x) {
x.forEach(async doc => {
try {
console.log(`deleting: ${collectionName}/${doc.id}`)
await doc.ref.delete();
} catch (error) {
console.log(error)
}
})
}
})
}
虽然它不会在所有文档上重复尝试,但这确实令人困惑。例如,我有三个文档,当我 运行 这个时,它遍历了两个文档两次,一个文档一次。我在另一组有十几个左右的文档上尝试了它,看起来它有相同的结果(尽管我对 1:3 比率并不乐观)。
您正在订阅某个查询,当然,当您删除一个或多个元素时,结果会发生变化。我修复了您的代码,因此您只需删除一次订阅,而不是订阅。
async deleteDocuments<T>(collectionName: string, fieldToCheck: string, stringValueToCheck: string) {document ID to 'id'
const docs = await this._afs.collection(collectionName)
.ref.where(fieldToCheck, '==', stringValueToCheck)
.get();
docs.forEach(doc => doc.ref.delete());
}