0

In my firestore database, I have user generated posts which have a topic element attached to it.

Users subscribe to topics and they are stored on the user's profile database.

Now, I need to loop through all of the user's subscribed topics, and I want to find the most recent 10 posts that have a topic that is also in the user's subscribed_to object.

So what I'm doing is this:

  //establish the query.
  var query = this.afs.collection('posts').ref
  .orderBy('created', 'desc')
  .limit(11);

  //loop through the user's subscribed_to data
  for(var topic in this.userData.subscribed_to) {
    //add each topic to the where query
    query = query.where('topic', '==', topic);
  }

  query.get().then((results) => {
    //..rest of the code
  })

The problem seems to be that the query adding the where's as an AND instead of an OR, meaning a post would need all the topics that the user is subscribed to...

How can I do it that it goes by OR and finds the posts that contains topic x, or topic y, or topic z...

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Simon
  • 2,498
  • 3
  • 34
  • 77
  • Firestore does not support OR conditions in queries. The best approach is to perform a separate query for each condition, and join them client-side. These questions might be a good starting point for doing that: https://stackoverflow.com/search?q=%5Bgoogle-cloud-firestore%5D%5Bangularfire2%5D+join – Frank van Puffelen Jun 08 '19 at 23:04
  • @FrankvanPuffelen What if I have to make 25 different queries but I only need the 10 most recent `posts` from from the 25 different queries.. I'd have to get the 10 most recent `posts` for all queries and then order them... Is there no better way? – Simon Jun 08 '19 at 23:29
  • Firestore doesn't support OR conditions in queries. Also see the link above, [docs on query limitations](https://firebase.google.com/docs/firestore/query-data/queries#query_limitations), this [long thread on github](https://github.com/firebase/firebase-js-sdk/issues/321), and these answer [1](https://stackoverflow.com/a/46633294) and [2](https://stackoverflow.com/a/47019670). The only alternative is to store the combinations you want to query on too, so with things like `topicA_or_topicB`, `topicA_or_topicC`. That sometimes is possible, but here the number of combinations would explode quickly – Frank van Puffelen Jun 09 '19 at 00:02
  • @FrankvanPuffelen Thanks for the info. Would Algolia be a solution for my needs? I know Google recommends Algolia in some situations... – Simon Jun 09 '19 at 21:47
  • I honestly don't know enough about Algolia to answer that. But such recommendations are off-topic on Stack Overflow anyway, since they tend to attract overly opinionated answers. I'd say, check the Algolia docs, and give it a try. – Frank van Puffelen Jun 09 '19 at 22:19

0 Answers0