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.
CodePudding user response:
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.