Reputation: 623
How can I get a reference to the results of a where
clause? My database is structured like this:
- Restaurants
- Restaurant 1
- Ratings (sub collection)
- Statistics
So I have a restaurants collection where each doc is specific restaurant. And in each doc, there is a subcollection called ratings. I'm trying to get a document reference to restaurant 1 so I can add some general statistics to it, and also a reference to the subcollection so I can add a rating. I'm currently stuck on getting a reference to the restaurant 1 because I use a where clause, which doesn't return a reference.
var restaurantRef = firestore.collection("restaurants").where("name", "==", "Neubig Hall")
function addFeedback(data) {
return firestore.runTransaction((transaction) => {
var feedbackRef = restaurantRef.get().then(snapshot => {snapshot.forEach(doc => doc.ref.collection("feedback"))});
It's saying restaurantRef
is not a document reference. I'm using this in a React Native app.
Upvotes: 0
Views: 6499
Reputation: 317712
As you can see from the API documentation, where() returns a Query object. It's not a DocumentReference.
Even if you think that a query will only return one document, you still have to write code to deal with the fact that it could return zero or more documents in a QuerySnapshot object. I suggest reviewing the documentation on queries to see examples.
Also note that you can't use a Query object in a transaction. Transactions require a DocumentReference, which again, you don't have here.
If you do want to execute the query and work with the documents it returns, it will go more like this:
const restaurantQuery = firestore.collection("restaurants").where("name", "==", "Neubig Hall")
restaurantQuery.get().then(querySnapshot => {
if (!querySnapshot.empty) {
const snapshot = querySnapshot.docs[0] // use only the first document, but there could be more
const documentRef = snapshot.ref // now you have a DocumentReference
// ... use your DocumentReference ...
}
else {
// decide what you want to do if the query returns no documents.
}
})
Upvotes: 4
Reputation: 83163
You have a typo in your code: you call restauranteRef.get()
with an e
at the end of restaurant
, while your query is declared as restaurantRef
, without e
.
You should do:
function addFeedback(data) {
return firestore.runTransaction((transaction) => {
var feedbackRef = restaurantRef.get()then(...) // <- without e
// ...
}
Upvotes: 0