flowoverstack
flowoverstack

Reputation: 112

how do i get a document based on whats in its subcollection firestore?

I have a firestore database that looks like this : posts(collection)/post (document)/upvote (collection)/userID (document). now for example my user id is 1234 so it would look like this.

posts/dogs are cool/upvote/1234(userid)

id also like to add that the end document name is the userid and inside of it is just a property that says exists: true this is just so its not auto-deleted.

the goal for me is to go in and check if my user has upvoted on this post and if they have id like to return the post Document and not the upvote document. it's pretty much functionality where id likes to show the posts that I've upvoted. im using next js and firestore which im a little new to ive tried onsnapshot with a query but it seems like it might be something big that im missing.

Upvotes: 0

Views: 29

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598648

Firestore queries can only filter on data that is in the documents that they return. So if you're looking to return documents from the posts collection, you can only filter on data in those documents - not from the documents in the upvote collection under it.

The solution is usually to make sure you have some data about the votes in the posts documents. For example, if you store an upvoteCount in each document in posts, you can use that for the query - and implement more use-cases, such as get your most-upvoted posts. You'll have to update the document in posts whenever a relevant document is written (or deleted) under its upvotes collection.

Upvotes: 1

Related Questions