Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to query for a single field in firestore 9

I am trying to query the doc for data. I found out how to query using the flowing logic

const docRefCol = doc(db, 'UsersCollection', uid);

interface objectData {
   field1Obj: { [key: string]: any };
   field2Arr: [];
 }

 let obj: objectData = { field1Obj: {}, field2Arr: [] };
  await getDoc(docRefCol).then((docSnap) => {
   Object.assign(obj, docSnap.data());  
 });
  
  console.log(obj)

The issue with this is I want an immutable way to extract data. Plus anther way to query for single field (let’s say field1Obj), rather than calling the whole document.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There isn’t any way to get a few fields (at least not in client SDKs). But you can destruct the object and get the fields you need (or filter in case you are querying multiple objects).

let obj: objectData = { field1Obj: {}, field2Arr: [] };

await getDoc(docRefCol).then((docSnap) => {
  const { field1Object, field2Arr, ...rest } = docSnap.data()
  obj = { field1Object, field2Arr }
});

In case of a QuerySnapshot, it could be like:

await getDocs(query).then((querySnap) => {
  const docs = querySnap.docs.map((doc) => {
    const { field1Object, field2Arr, ...rest } = doc.data()
    return { field1Object, field2Arr }
  })
});

It surely won’t reduce amount of data being fetched from database but selecting fields is currently supported by Admin/server side SDKs only.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading