Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Firestore query to retrieve users based on last connection and presence of field

I have a Firestore collection called users that contains user documents. Each user document has an optional field called previewPosts, which is an array representing the user’s four most recent posts. Additionally, there is another field called lastConnection that stores the timestamp of the user’s last online connection.

I want to implement a query on the users collection that retrieves the top 10 users based on their last connection and ensures that they have the optional previewPosts field defined with at least one post in the array.

How can I construct a Firestore query to achieve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried the following:

const query = firestore
  .collection("users")
  .orderBy("lastConnection", "desc")
  .orderBy("previewPosts");

Is creating an extra field the best approach?

  const query = firestore
    .collection("users")
    .where("hasPreviewPhotos", "==", true)
    .orderBy("lastConnection", "desc");

>Solution :

Yes, creating an extra field is likely the best way. You could make it be a count rather than a boolean if you wanted to order by how many previews rather than just the existence, and this would later allow you to filter based on the number too (say "only users with more than 2 previews").

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading