updateDocInBatch method

Future<TurboResponse<WriteBatchWithReference<Map<String, dynamic>>>> updateDocInBatch({
  1. required TurboWriteable writeable,
  2. required String id,
  3. WriteBatch? writeBatch,
  4. TurboTimestampType timestampType = TurboTimestampType.updatedAt,
  5. String? collectionPathOverride,
})

Updates documents using a batch operation

Modifies multiple documents atomically while preserving unchanged fields Automatically manages timestamps based on timestampType

Parameters: writeable data to update, must implement TurboWriteable id unique identifier of the document writeBatch optional existing batch to add to timestampType type of timestamp to add when updating collectionPathOverride override path for collection groups

Returns TurboResponse containing:

  • Success with batch and document reference
  • Fail with validation or operation errors

Features:

  • Atomic updates
  • Automatic validation
  • Timestamp management
  • Creates new batch if none provided
  • Error logging

Example:

final batch = firestore.batch();
final user = User(name: 'John Updated');
final response = await api.updateDocInBatch(
  writeable: user,
  id: 'user-123',
  writeBatch: batch,
);
response.when(
  success: (result) async {
    await result.writeBatch.commit();
    print('Updated user ${result.documentReference.id}');
  },
  fail: (error) => print('Error $error'),
);

See also: updateDoc single document updates createDocInBatch batch creation

Implementation

Future<TurboResponse<WriteBatchWithReference<Map<String, dynamic>>>>
    updateDocInBatch({
  required TurboWriteable writeable,
  required String id,
  WriteBatch? writeBatch,
  TurboTimestampType timestampType = TurboTimestampType.updatedAt,
  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.',
  );
  final TurboResponse<WriteBatchWithReference<Map<String, dynamic>>>?
      invalidResponse = writeable.validate();
  if (invalidResponse != null && invalidResponse.isFail) {
    _log.warning(
      message: 'TurboWriteable was invalid!',
      sensitiveData: null,
    );
    return invalidResponse;
  }
  try {
    _log.info(message: 'TurboWriteable is valid!', sensitiveData: null);
    _log.debug(
      message: 'Creating document with batch..',
      sensitiveData: SensitiveData(
        path: collectionPathOverride ?? _collectionPath(),
        id: id,
        isBatch: writeBatch != null,
        updateTimeStampType: timestampType,
      ),
    );
    final nullSafeWriteBatch = writeBatch ?? this.writeBatch;
    final documentReference = getDocRefById(id: id);
    _log.debug(message: 'Creating JSON..', sensitiveData: null);
    final writeableAsJson = timestampType.add(
      writeable.toJson(),
      createdAtFieldName: _createdAtFieldName,
      updatedAtFieldName: _updatedAtFieldName,
    );
    _log.debug(
      message: 'Updating data with writeBatch.update..',
      sensitiveData: SensitiveData(
        path: collectionPathOverride ?? _collectionPath(),
        id: documentReference.id,
        data: writeableAsJson,
      ),
    );
    nullSafeWriteBatch.update(
      documentReference,
      writeableAsJson,
    );
    _log.info(
      message:
          'Adding update to batch done! Returning WriteBatchWithReference..',
      sensitiveData: null,
    );
    return TurboResponse.success(
      result: WriteBatchWithReference(
        writeBatch: nullSafeWriteBatch,
        documentReference: documentReference,
      ),
    );
  } catch (error, stackTrace) {
    _log.error(
      message: 'Unable to update 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: 'updateDocInBatch(id: $id)',
    );

    return TurboResponse.fail(error: exception);
  }
}