goodonion
goodonion

Reputation: 1789

How do I query ordering documents by multiple computed values in Firestore?

Let's I had documents contain two fields 'likeCount' and 'viewCount'. Is it possible to order them by a sum of those two fields?

If not, how do I implement ordering by popularity? Ordering by popularity is a common feature in a variety of apps but I can't find any documentation or tutorials for this.

Upvotes: 0

Views: 135

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83191

One solution is to have an extra field in each document which holds the value of the sum. Then you can easily sort based on this value.

To update this field, you can either do it when you update the document from your app, OR, if you don't have the info in the app when you update the doc (i.e. it would require fetching the document to get the value of the two fields) you can update the value in the backend, with a Cloud Function.

For example, a Cloud Function along the following lines would do the trick:

exports.updateGlobalCount = functions.firestore
    .document('collection/{docId}')
    .onUpdate((change, context) => {

        const previousValue = change.before.data();
        const newValue = change.after.data();

        if (previousValue.likeCount !== newValue.likeCount || previousValue.viewCount !== newValue.viewCount) {     
            return change.after.ref.update({ globalCount: newValue.likeCount + newValue.viewCount })
        } else {
            return null;
        }
    });

Upvotes: 2

Related Questions