Simon
Simon

Reputation: 2538

Firebase firestore complicated query

I'm wondering if this is possible, and if it's a good solution to my problem.

I want users to be able to subscribe to content. The content is associated with an id.. for instance:

'JavaScript': 1,
'C++': 2,
'Python': 3,
'Java': 4,

Let's say a user subscribes to 1, 3, and 4.

So their user json data would appear as:

'subscribed_to': [1,3,4]

Now in my firestore, I have posts. Each post gets assigned a content_id (1-4 for instance), and so when I query for the content that this user is subscribed to, how would I do that so as effectively as possible?

Upvotes: 2

Views: 2946

Answers (1)

andresmijares
andresmijares

Reputation: 3744

This is indeed a complex but common case, I would recommend to set a data structure similar to:

{ 
   "subscriptions" {
      javascript: { ... },
      python: { ... },
      java: { ... }
   },
   "users": {
      1: {
        subscribed_to: ['javascript', 'python']
      }
   }
}

It's very important that on your subscribed_to prop you use the doc name, cause this is the part that allows you to query them (the docs).

the big problem, how do I query this data? I don't have joins!

Case 1:

Assuming you have your user data when you apply load...

const fetchDocs = async (collection, docs) => {
    const fetchs = docs.map(id => collection.doc(id).get())
    const responses = await Promise.all(fetchs)
    return responses.map(r => r.data())
}

const userSubscriptions = ['javascript', 'python']
const mySubscriptions = await fetchDocs(`subscriptions`, userSubscriptions)

Behind the scene, the sdk will group all the queries and do its best efforts to deliver em together. This works good, I'm 99% sure you still have to pay for each query individually each time the user logs in.

Case 2:

Create a view dashboard collection and pre-calculate the dashboard behind the scene, this approach involves cloud functions to listen or changes on the user changes (and maybe subscriptions as well) and copy each individual doc into another collection, let's say subscriptions_per_users. This is a more complex approach, I will require more time to explain but if you have a big application where costs are important and if the user is going to subscribe to a lot of things, then you might want to investigate about it.

Source: My own experience... a little of google can also help, there seems to be a lot of opinions about it, find what works best for you.

Upvotes: 4

Related Questions