getById method
Retrieves a document by its unique identifier
Returns raw Firestore data without type conversion. Useful for direct data access or when type conversion is not needed
Parameters:
id
unique identifier of the document
collectionPathOverride
override path for collection groups
Returns TurboResponse
containing:
- Success with document data
- Empty fail when document not found
- Fail with error details on operation failure
Features:
- Raw data access
- Local ID field management
- Document reference handling
- Error logging
Example:
final response = await api.getById(id: 'user-123');
response.when(
success: (data) => print('Found user ${data['name']}'),
fail: (error) => print('Error $error'),
);
See also:
- getByIdWithConverter type-safe document retrieval
- getDocRefById document reference access
Implementation
Future<TurboResponse<Map<String, dynamic>>> getById({
required String id,
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: 'Finding without converter..',
sensitiveData: SensitiveData(
path: collectionPathOverride ?? _collectionPath(),
id: id,
),
);
final result = (await getDocRefById(
id: id,
collectionPathOverride: collectionPathOverride,
).get(_getOptions))
.data();
if (result != null) {
_log.info(
message: 'Found item!',
sensitiveData: null,
);
return TurboResponse.success(result: result);
} else {
_log.warning(
message: 'Found nothing!',
sensitiveData: null,
);
return TurboResponse.fail(
error: 'Document not found',
title: 'Not Found',
message: 'The requested document was not found');
}
} catch (error, stackTrace) {
_log.error(
message: 'Unable to find 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: 'getById(id: $id)',
);
return TurboResponse.fail(error: exception);
}
}