I'm trying to query a very simple collection that looks like this:
urls: {
07WmGw7w0N8JiD7j1P60: {
url: "www.yay.com"
},
07WmGw7w0N8JiD7j1P60: {
url: "www.anotherurl.com"
}
}
So my code looks like this:
export async function checkDoc() {
try {
const urlsRef = await collection(db, "urls");
const q = await query(urlsRef, where("url", "==", "www.yay.com"));
console.log(q)
return q
} catch (e) {
console.error("Error querying document: ", e);
return e.response
}
}
But the response I'm getting is like this:
As far as I can tell, this is exactly how this is done in the documentation. I already trawled similar answers on Stackoverflow, but they mostly use the Web v8 chaining method which I'm not sure how to implement with my current setup. Is the issue with the way I'm using firebase or with the way I'm making the asynchronous call?
CodePudding user response:
This is because you actually don't query the database but you just build a query
(i.e. the q
object).
To query/fetch the database according to this query you need to pass this query
to the getDocs()
method, as follows:
export async function checkDoc() {
try {
const urlsRef = collection(db, "urls");
const q = query(urlsRef, where("url", "==", "www.yay.com"));
const querySnapshot = await getDocs(q);
querySnapshot.forEach(docSnap => {
// ....
})
return ... // Generate the returned object in the forEach loop, see link below
} catch (e) {
console.error("Error querying document: ", e);
return e.response
}
}
This is shown here in the Firestore documentation. Note that the collection()
and query()
methods are not asynchronous, hence there is no need to call them with await
. On the opposite, getDocs()
is asynchronous.