Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firestore orderby on subproperty (subcollection)

Using the new firestore, I have a structure that looks like this:

{
    ...
    "username": "mr_jones",
    "date_created": 1508395138572,
    "stats": {
        "posts": 143,
        ...
    },
    ...
}

According to the documentation, I can order and limit my query in order to filter data based on a where clause. How can I order this data based on stats.posts?

i.e.

usersRef.orderBy('stats.posts').limit(15);
like image 758
Felipe Avatar asked Oct 20 '17 00:10

Felipe


1 Answers

Looks like you have a typo in your code:

usersRef.orderBy('stats.post').limit(15);

The field name should be stats.posts according to your previous structure:

usersRef.orderBy('stats.posts').limit(15);

I've double checked this works. In the console I created a collection called tester that stores 4 documents. Each document has a stats.posts property set to a number 1 through 4. The below code prints out 1, 2, 3. If I remove the limit it prints out 1, 2, 3, 4. If I also remove the order by it prints out 2, 1, 3, 4.

db.collection('tester').orderBy('stats.posts').limit(3).get().then(function(querySnapshot) {
    querySnapshot.forEach(function(documentSnapshot) { 
        console.log(documentSnapshot.data().stats.posts);
    });
});
like image 75
Dan McGrath Avatar answered Oct 02 '22 23:10

Dan McGrath