0

This function is in Cloud Functions, I would like to know how I can get only one field of a specific document, and not just fetch all document data. My Code:

export const onNewOrder = functions.firestore.document("/orders/{orderId}").onCreate(async (snapshot, context) => {
  const orderId = context.params.orderId;

  // Where do I specify the data from which field I want to fetch?
  const snap = await admin.firestore().collection("orders").doc(orderId).get();
  console.log(snap.data());
});

Where do I specify the data from which field I want to fetch?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Eric Melo
  • 45
  • 8

1 Answers1

0

Firestore client-side SDKs always retrieve the entire document. There is no way to specify that only certain fields should be retrieved from the server.

This option does exist in the server-side/Admin SDKs, such as the one for Node.js.

For more on this, see How to access a specific field from Cloud FireStore Firebase in Swift, Firestore get document except some fields

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Yes, but how do I get the DocumentSnapshot that is returned and select which Map field I want set in a variable? On Dart it would be something like: – Eric Melo Jul 30 '21 at 10:38
  • `final DocumentSnapshot docUser = await firestore.collection('users').document(currentUser.uid).get(); name = docUser.data['name'] as String;` – Eric Melo Jul 30 '21 at 10:39
  • How do I do the same in TS? – Eric Melo Jul 30 '21 at 10:39
  • You mean something like `console.log(snap.data()["name"])`? – Frank van Puffelen Jul 30 '21 at 15:02
  • Yes, I've tried to write like this, but it's not accepted, and it shows the error "Possibly the object is null" – Eric Melo Jul 30 '21 at 16:02
  • So did you then add a null check (`if snap.data() != null)`), or hard-cast to non-null (`snap.data()!.name`)? – Frank van Puffelen Jul 30 '21 at 16:25
  • Thanks for your time, I figured out how to access a value from a map. Simply put: `snap.get("value")` – Eric Melo Jul 30 '21 at 22:31
  • @FrankvanPuffelen is there any particular reason _why_ it's not possible to specify only certain fields be returned? While I understand such functionality may facilitate bad behaviors if used for faux-security measures, there are legitimate use cases where reducing a payload size delivered to a client would be very helpful. – bsplosion Dec 30 '21 at 17:22
  • It would thoroughly complicate the client-side caching, since we'd no longer be able to assume two snapshots of the same document would be equivalent. – Frank van Puffelen Dec 30 '21 at 17:52