Home > Blockchain >  How to fetch a single Field from a Firestore document in a collection from Firebase?
How to fetch a single Field from a Firestore document in a collection from Firebase?

Time:04-14

I am trying to fetch only a Map field stored in a document of Firestore collection instead of fetching the whole document which is obviously more time taking and bandwidth consuming.

This is the way I am getting my data from a Map Field which is defined inside a Document named by UserID of a particular user -

DocumentSnapshot snap = await driversRef.doc(user!.uid).get();
email = ((snap.data() as Map)['profile'] as Map)['email'];
name = ((snap.data() as Map)['profile'] as Map)['name'];
mobile = ((snap.data() as Map)['profile'] as Map)['mobile'];
age = ((snap.data() as Map)['profile'] as Map)['age'];
address = ((snap.data() as Map)['profile'] as Map)['address'];

But as said above, it is getting the entire document in the first line of the code.

My Firestore Collection Image

Is there any way i can get just a particular field of any data type from a Firestore document?

CodePudding user response:

I am trying to fetch only a Map field stored in a document of Firestore collection instead of fetching the whole document which is obviously more time taking and bandwidth-consuming.

There is no way you can do that. All Firestore listeners fire on the document level. This means that you cannot only get the value of a Map field from a document. It's the entire document or nothing. That's the way Firestore works, and unfortunately, we cannot change that.

Is there any way I can get just a particular field of any data type from a Firestore document?

No. However, if you only want to read the value of a single property then you should consider storing only that property in a document. Or store that single property in the Realtime Database. This practice is called denormalization, and it's a quite common practice when it comes to NoSQL databases.

  • Related