I have following code:
I use cloud firestore as database
UserModel:
class DbUser {
String id;
final String authUserID;
final String userName;
final List<String>? itemsForSale;
final List<String>? itemFavourites;
final List<String>? bids;
DbUser(
{this.id = '',
required this.authUserID,
required this.userName,
this.itemsForSale,
this.itemFavourites,
this.bids});
Map<String, dynamic> toJson() => {
'id': id,
'authUserID': authUserID,
'userName': userName,
'itemsForSale': itemsForSale,
'itemFavourites': itemFavourites,
'bids': bids,
};
static DbUser fromJson(Map<String, dynamic> json) => DbUser(
id: json['id'],
authUserID: json['authUserID'],
userName: json['userName'],
itemsForSale: json['itemsForSale'] is Iterable
? List.from(json['itemsForSale'])
: null,
itemFavourites: json['itemFavourites'] is Iterable
? List.from(json['itemFavourites'])
: null,
bids: json['bids'] is Iterable ? List.from(json['bids']) : null,
);
}
Repository class
final _firestoreDB = FirebaseFirestore.instance;
Future<DbUser?> getDBUserByDBUserId({required String dbUserID}) async {
final docUser = _firestoreDB.collection('users').doc(dbUserID);
final snapshot = await docUser.get();
if (snapshot.exists) {
return DbUser.fromJson(snapshot.data()!);
}
return null;
}
snapshot.exists returns false.
I do not understand why?
my snapshot returns null but I do not see why it does that, could somebody please help me?
Thank you
2
Answers
Space
found my problem, there was a space before my Id that had been retreived, I must have accedentally put it there when creating the database...
Looking at the screenshot of the document you shared, the document ID in the second column is different from the value of
authUserID
in the third column. So it seems like you added the document by callingadd
, which means that Firestore generates a unique ID for you.You then create a reference to the document with this code:
But here you are specifying
dbUserID
as the document ID, which doesn’t match what you did when you created the document. Firestore now looks for a document with an ID that is the same as the user ID, which doesn’t exist and thus gives you a snapshot whereexists
isfalse
.If you want to find the document for the user in your current structure, you can use a query to do so:
But a better solution might be to actually store the user document under its user ID. You can specify the document ID as shown in the documentation on setting a document. So here you’d call
.document('theuserid').set(...)
instead ofadd(...)
.