简体   繁体   中英

Best way to keep track of counter variables for documents in a collection

My project has a feature that allows following/followers similar to a lot of social.networks. Because I will likely get the count of these numbers very often, I figured it would be best to create a separate measure for the follower/following count so I don't have to.get() all of them to get a count. I am currently deciding between 3 options to keep track of this counter variable.

Option 1 (Keep counter & collection separate)

[User Collection]           [Followers Collection]
(uid)                       (uid)
  -username                   -uid_1
  -follower_count             -uid_2

Option 2 (Put counter and data in separate collection, make a sub-collection for the data)

[User Collection]           [Followers Collection]
(uid)                       (uid)
 -username                   -count
                             -[Followers]
                               -uid_1
                               -uid_2

Option 3 (Keep it all in one collection and use arrays to get all data + count in one read -- Worried about this leading to document going over 1Mib limit)

[User Collection]
(uid)
 -username
 -following
    -[uid_1, uid_2]                             

Is there a glaring issue in doing it one of these ways? Or would all lead to the same costs/querying time at the end of the day?

Any time you have an array that can grow unbounded, it should probably be represented a documents in a subcollection. That's just how Firestore works. You can have an array if you want, but as you said, you risk going over the limit, and you have a very big problem that's even more difficult and expensive to solve than the cost of the reads and writes.

Whether or not you use a collection or subcollection is entirely up to you and how it best suits your queries. Since we don't know your queries or your anticipated security rules, it's not really possible to say which one is better. Pick the one that meets your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM