我希望能够删除子集合中的所有文档,作为android中事务的一部分。我找到了以下代码,但这是针对Node.js
的// First perform the query
db.collection('job_skills').where('job_id','==',post.job_id).get()
.then(function(querySnapshot) {
// Once we get the results, begin a batch
var batch = db.batch();
querySnapshot.forEach(function(doc) {
// For each doc, add a delete operation to the batch
batch.delete(doc.ref);
});
// Commit the batch
return.batch.commit();
}).then(function() {
// Delete completed!
// ...
});
非常感谢任何帮助!
谢谢!
答案 0 :(得分:1)
我在你的代码中看到的不是所谓的事务,它被称为批处理。因此,如果您想使用Android SDK删除集合中的所有文档,我建议您使用以下方法:
private void deleteCollection(final CollectionReference collection, Executor executor) {
Tasks.call(executor, new Callable<Object>() {
@Override
public Object call() throws Exception {
int batchSize = 10;
Query query = db.collection("job_skills").whereEqualTo("job_id", job_id);
List<DocumentSnapshot> deleted = deleteQueryBatch(query);
while (deleted.size() >= batchSize) {
DocumentSnapshot last = deleted.get(deleted.size() - 1);
query = collection.orderBy(FieldPath.documentId()).startAfter(last.getId()).limit(batchSize);
deleted = deleteQueryBatch(query);
}
return null;
}
});
}
这是deleteQueryBatch()
方法:
@WorkerThread
private List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
QuerySnapshot querySnapshot = Tasks.await(query.get());
WriteBatch batch = query.getFirestore().batch();
for (DocumentSnapshot snapshot : querySnapshot) {
batch.delete(snapshot.getReference());
}
Tasks.await(batch.commit());
return querySnapshot.getDocuments();
}