Currently, I have a React application connected to Firestore. I followed the official documentation on adding custom objects to Firestore via the help of withConverter function.
Now I want to read all the data I uploaded to Firestore into my app as a custom object again. But the documentation on Firestore did not show how to pull it off. The documentation only showed getting one document as custom objec and get multiple documents. But not a combination of both which I need.
Maybe I’m missing out some concepts, am I not supposed to get multiple documents as custom objects or something else? Any help is very much appreciated!
My data converter function:
const dataConverter = {
toFirestore: (stock) => {
return {
brand: stock.brand,
model: stock.model,
serialNum: stock.serialNum,
stock: stock.stock,
location: stock.location,
date: stock.date,
inventoryUID: stock.inventoryUID
}
},
fromFirestore: (snapshot, options) => {
const data = snapshot.data(options);
return new Stocks(data.brand, data.model, data.serialNum, data.stock, data.location, data.date, data.inventoryUID);
}
}
Let me know if any additional information is required. Thanks a lot!
>Solution :
I’ve never used withConverter before, but given that a Query object also has a withConverter method, I expect you just call that on the Query object similar to how you call it on a DocumentReference:
// for a single document
const ref = doc(db, "cities", "LA").withConverter(cityConverter);
// for multiple documents
const q = query(collection(db, "cities"), where("capital", "==", true))
.withConverter(cityConverter);