deleteDocInBatch method
Deletes documents using a batch operation
Removes multiple documents atomically Creates new batch if none provided
Parameters:
id
unique identifier of the document
writeBatch
optional existing batch to add to
collectionPathOverride
override path for collection groups
Returns TurboResponse
containing:
- Success with batch and document reference
- Fail with operation errors
Features:
- Atomic deletion
- Creates new batch if none provided
- Collection group support
- Error logging
Example:
final batch = firestore.batch();
final response = await api.deleteDocInBatch(
id: 'user-123',
writeBatch: batch,
);
response.when(
success: (result) async {
await result.writeBatch.commit();
print('Deleted user ${result.documentReference.id}');
},
fail: (error) => print('Error $error'),
);
See also: deleteDoc single document deletion updateDocInBatch batch updates
Implementation
Future<TurboResponse<WriteBatchWithReference<Map<String, dynamic>>>>
deleteDocInBatch({
required String id,
WriteBatch? writeBatch,
String? collectionPathOverride,
}) async {
assert(
_isCollectionGroup == (collectionPathOverride != null),
'Firestore does not support finding a document by id when communicating with a collection group, '
'therefore, you must specify the collectionPathOverride containing all parent collection and document ids '
'in order to make this method work.',
);
try {
_log.debug(
message: 'Deleting document with batch..',
sensitiveData: SensitiveData(
path: collectionPathOverride ?? _collectionPath(),
id: id,
isBatch: writeBatch != null,
),
);
final nullSafeWriteBatch = writeBatch ?? this.writeBatch;
final documentReference =
getDocRefById(id: id, collectionPathOverride: collectionPathOverride);
_log.debug(
message: 'Deleting data with writeBatch.delete..',
sensitiveData: null,
);
nullSafeWriteBatch.delete(documentReference);
_log.info(
message:
'Adding delete to batch done! Returning WriteBatchWithReference..',
sensitiveData: null,
);
return TurboResponse.success(
result: WriteBatchWithReference(
writeBatch: nullSafeWriteBatch,
documentReference: documentReference,
),
);
} catch (error, stackTrace) {
_log.error(
message: 'Unable to delete document with batch',
sensitiveData: SensitiveData(
path: collectionPathOverride ?? _collectionPath(),
id: id,
),
error: error,
stackTrace: stackTrace,
);
// Convert to TurboFirestoreException and wrap in TurboResponse
final exception = TurboFirestoreException.fromFirestoreException(
error,
stackTrace,
path: collectionPathOverride ?? _collectionPath(),
query: 'deleteDocInBatch(id: $id)',
);
return TurboResponse.fail(error: exception);
}
}