With the Client SDKs it is not possible to get only a subset of the fields for a Document. When you fetch a Document you get it with all its fields.
Here are three possible approaches:
Dernomalize your data: You create another collection which contains documents that only have the fields you want to display in the front end. The complexity is that you need to keep the two collections in sync: when you create/modify/delete a doc in the master collection, you need to update the other collection. This can be done from your front-end (e.g. you write to the two collections in a batched write) or with a Cloud Function, triggered in the back-end with an onWrite
trigger. In terms of security, you open read access only to the second collection, not to the master one.
Use the Firestore REST API: With the REST API you can use a DocumentMask
when fetching documents, which will "restrict a get operation on a document to a subset of its fields. ". Note, however, that a "hacker" could get the collection ID and fetch the documents without the Mask.
Use a Cloud Function to access the Firestore documents. With a Cloud Function, you have full control on what you want to send back to the front-end, since you query the collection from within the Cloud Function and build the response in the Cloud Function. However, using a Cloud Function instead of a Client SDK has several drawbacks: see this article for more details.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…