Home > Net >  Use multiple orderBy in Firebase
Use multiple orderBy in Firebase

Time:08-30

I am building an app where the user can get the tasks sent to him and the tasks sent by him. The user can send tasks for himself and these tasks can only be obtained in the list of tasks sent to the user. If the user wants to get the tasks sent by him, the tasks sent to self cannot be obtained. The tasks also need to be ordered by creation date. So I did the following:

Get tasks sent to the user:

this.db.collection(this.taskCollection)
.where('to', '==', phoneNumber)
.where('accepted', '==', true)
.orderBy('createdAt', 'desc')

This case works perfectly, I can get all the tasks sent to the user ordered by createdAt.

The problem arises when I try to get the tasks sent by the user. As I want all tasks sent the user, except those sent to himself, I did the following:

this.db.collection(this.taskCollection)
.orderBy('to', 'desc')
.where('to', '!=', phoneNumber)
.where('from', '==', phoneNumber)
.where('accepted', '==', true)
.orderBy('createdAt', 'desc')

In this case the tasks are only been ordered by "to" fields, they are not been ordered by createdAt. How can I get theses tasks ordered by createdAt?

CodePudding user response:

That is the expected behavior. In order to do a not-equals filter on to, you'll first need to order on that field, and thus the results are going to be first in order of to values and only then in order of createdAt.

If that's not how you want to display/process the items in your code, you'll have to reorder the items in your application code. I recommend having a look at:

  • Related