0

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?

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
DebRC
  • 13
  • 2
  • In addition to Alex's answer, this can be done by using `select()` in NodeJS SDKs as explained [here](https://stackoverflow.com/q/48312485/13130697). However this might more useful you are fetching multiple documents and want to return some aggregated data. – Dharmaraj Apr 14 '22 at 08:11

1 Answers1

4

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.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • 1
    Thanks a lot, i'll try to do the second thing you suggested, storing it in a RTDB. Sounds, a lot better. – DebRC Apr 14 '22 at 13:49