findDocRef method
Finds a DocumentReference
of type Map<String, dynamic> based on given id
.
If _tryAddLocalId
is true then your data will also contain a local id field based
on the _idFieldName
specified in the constructor. Add this id field to your T
and you will
have easy access to the document id at any time.
If _tryAddLocalDocumentReference
is true then your data will also contain a local reference field based
on the _documentReferenceFieldName
specified in the constructor. Add this reference field to your T
and you will
have easy access to the document reference at any time.
If you rather want to retrieve data in the form of T
consider using the
findDocRefWithConverter method instead.
Implementation
DocumentReference<Map<String, dynamic>> findDocRef({
required String id,
String? collectionPathOverride,
}) {
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.',
);
_log.info(
message: 'Finding document..',
sensitiveData: _shouldNotSensitiveInfo
? null
: SensitiveData(
path: collectionPathOverride ?? _collectionPath(),
id: id,
),
);
return _firebaseFirestore
.doc('${collectionPathOverride ?? _collectionPath()}/$id')
.withConverter<Map<String, dynamic>>(
fromFirestore: (snapshot, _) {
final data = snapshot.data() ?? {};
try {
return data
.tryAddLocalId(
snapshot.id,
idFieldName: _idFieldName,
tryAddLocalId: _tryAddLocalId,
)
.tryAddLocalDocumentReference(
snapshot.reference,
referenceFieldName: _documentReferenceFieldName,
tryAddLocalDocumentReference: _tryAddLocalDocumentReference,
);
} catch (error) {
_log.error(
message:
'Unexpected error caught while adding local id and document reference',
sensitiveData: _shouldNotSensitiveError
? null
: SensitiveData(
path: collectionPathOverride ?? _collectionPath(),
id: snapshot.id,
data: data,
),
);
rethrow;
}
},
toFirestore: (data, _) {
try {
return data
.tryRemoveLocalId(
idFieldName: _idFieldName,
tryRemoveLocalId: _tryAddLocalId,
)
.tryRemoveLocalDocumentReference(
referenceFieldName: _documentReferenceFieldName,
tryRemoveLocalDocumentReference: _tryAddLocalDocumentReference,
);
} catch (error) {
_log.error(
message:
'Unexpected error caught while removing local id and document reference',
sensitiveData: _shouldNotSensitiveError
? null
: SensitiveData(
path: collectionPathOverride ?? _collectionPath(),
id: id,
data: data,
),
);
rethrow;
}
},
);
}