'Convert DocumentReference property into String from Firestore
I have a list of elements (Tickets) and since I can't convert the json because of one property (in this case user_id) being a document reference, how can I achieve to change only this property into a string (user_id)? It is written in Dart.
Code that won't work with DocumentReference:
QuerySnapshot<Map<String, dynamic>> querySnapshot.docs
.map((doc) => Ticket.fromJson(doc.data()))
.toList();
fromJson:
Ticket _$TicketFromJson(Map<String, dynamic> json) => Ticket(
id: json['id'] as String? ?? '',
createdAt: DateTime.parse(json['created_at'] as String),
price: (json['price'] as num).toDouble(),
userId: json['user_id'] as String,
);
I know that I can get the String path of the DocumentReference by using .getPath(). But how can alter it inside the map in the query above?
Solution 1:[1]
Here is a working solution:
final result = querySnapshot.docs.map((doc) {
final ticket = doc.data();
final dR = ticket['user_id'] as DocumentReference;
final path = dR.path;
ticket.update('user_id', (dynamic value) => path);
return Ticket.fromJson(ticket);
}).toList();
Maybe there is a more elegant way to accomplish the same result.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | B0r1 |
