deleteDoc method

Future<TurboResponse> deleteDoc({
  1. required String id,
  2. WriteBatch? writeBatch,
  3. String? collectionPathOverride,
  4. Transaction? transaction,
})

Deletes a document from Firestore

Permanently removes document and all its data Supports batch and transaction operations

Parameters: id unique identifier of the document writeBatch optional batch to include this operation in collectionPathOverride override path for collection groups transaction optional transaction to include this operation in

Returns TurboResponse containing:

  • Empty success when document is deleted
  • Empty fail on operation failure

Features:

  • Batch operation support
  • Transaction support
  • Collection group support
  • Error logging

Example:

final response = await api.deleteDoc(id: 'user-123');
response.when(
  success: (_) => print('Deleted user'),
  fail: (error) => print('Error $error'),
);

See also: deleteDocInBatch batch deletion updateDoc document updates

Implementation

Future<TurboResponse> deleteDoc({
  required String id,
  WriteBatch? writeBatch,
  String? collectionPathOverride,
  Transaction? transaction,
}) 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..',
      sensitiveData: SensitiveData(
        path: collectionPathOverride ?? _collectionPath(),
        id: id,
        isBatch: writeBatch != null,
      ),
    );
    if (writeBatch != null) {
      _log.debug(
        message: 'WriteBatch was not null! Deleting with batch..',
        sensitiveData: null,
      );
      final lastBatchResponse = await deleteDocInBatch(
        id: id,
        writeBatch: writeBatch,
        collectionPathOverride: collectionPathOverride,
      );
      _log.debug(
        message: 'Checking if batchDelete was successful..',
        sensitiveData: null,
      );
      final batchResult = _handleBatchResponse(lastBatchResponse);
      if (batchResult != null) {
        _log.debug(
          message: 'Last batch was added with success! Committing..',
          sensitiveData: null,
        );
        await batchResult.writeBatch.commit();
        _log.info(
          message: 'Committing writeBatch done!',
          sensitiveData: null,
        );
        return TurboResponse.success(
            result: null,
            title: 'Success',
            message: 'Document deleted successfully');
      } else {
        _log.error(
          message: 'Last batch failed!',
          sensitiveData: null,
        );
        return TurboResponse.fail(
            error: 'Failed to delete document',
            title: 'Error',
            message: 'Failed to delete document');
      }
    } else {
      _log.debug(
        message: 'WriteBatch was null! Deleting without batch..',
        sensitiveData: null,
      );
      final documentReference = getDocRefById(
          id: id, collectionPathOverride: collectionPathOverride);
      if (transaction == null) {
        _log.debug(
          message: 'Deleting data with documentReference.delete..',
          sensitiveData: null,
        );
        await documentReference.delete();
      } else {
        transaction.delete(getDocRefById(id: documentReference.id));
      }
      _log.info(
        message: 'Deleting data done!',
        sensitiveData: null,
      );
      return TurboResponse.success(
          result: null,
          title: 'Success',
          message: 'Document deleted successfully');
    }
  } catch (error, stackTrace) {
    if (transaction != null) {
      // Wrap and rethrow for transactions
      throw TurboFirestoreException.fromFirestoreException(
        error,
        stackTrace,
        path: collectionPathOverride ?? _collectionPath(),
        query: 'deleteDoc(id: $id)',
      );
    }

    _log.error(
        message: 'Unable to delete document',
        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: 'deleteDoc(id: $id)',
    );

    return TurboResponse.fail(
        error: exception,
        title: 'Error',
        message: 'Failed to delete document');
  }
}