skip to Main Content

likes[asdasd,sadsad] T
here is a list of UIDs for each post, I determine the most likes according to the length of this list. I want this list to come in order from the longest to the shortest, what should I do?
If I do orderBy descending true will it work?

2

Answers


  1. If likes is an array, and you want to order the documents according to the length of the array, then you have to add an extra field of type number, for example, likesLength, which will hold the length of the array. Then you can then perform a query and order the results ascending according to this field.

    One thing to note would be that you’ll have to update the array each time a new like is added or removed. This can be done from the client-side code, but more elegant it will be to use Cloud Functions for Firebase.

    Login or Signup to reply.
  2. You can’t sort by the length of the array

    https://firebase.google.com/docs/firestore/manage-data/data-types#data_types

    I would create a new filed called likesCount and use Cloud Function to update the numbers

    here is an example code:

    export const updateLikesCount = functions.firestore.document('posts/{postId}')
      .onUpdate(async (change, context) => {
    
        const beforeData = change.before.data();
        const afterData = change.after.data();
    
        // Check if the likes array has been updated
        if (beforeData.likes.length !== afterData.likes.length) {
    
          // Update the likes count
          await postRef.update({ likesCount: afterData.likes.length });
    
          console.log(`Updated likes count for post ${context.params.postId}: ${afterData.likes.length}`);
    
        }
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search