簡體   English   中英

如何在Firestore Android交易的子集合中遍歷文檔?

[英]How do you iterate through documents in a sub-collection within a transaction for firestore android?

我希望能夠刪除子集合中的所有文檔,這是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!
  // ...
}); 

任何幫助將不勝感激!

謝謝!

我在您的代碼中看到的不是交易,而是批處理。 因此,如果您想使用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();
}

即使Firebase團隊不建議刪除操作,因為它具有負面的安全性和性能影響,您仍然可以將其用於小型數據集。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM