Home > OS >  Firestore: multiple where()'s and orderBy()
Firestore: multiple where()'s and orderBy()

Time:12-13

Im making a flutter app, and in it I have posts called 'waves'. Id like to get them posted by a certain id, excluding blockedIds, and sorted by the time createdAt. When I try, I am getting the following error:

'conditionField == orders[0][0]': The initial orderBy() field "[[FieldPath([createdAt]), true]][0][0]" has to be the same as the where() field parameter "FieldPath([senderId])" when an inequality operator is invoked.

Which is coming from the following code:

initial = FirebaseFirestore.instance
          .collection('waves')
          .where('replyTo', isEqualTo: waveId);
      initial = initial.where('senderId', whereNotIn: blockerUserIds);
      initial = initial.orderBy('createdAt', descending: true);
      initial = initial.limit(5);
      query = await initial.get();

The suggestions I have read so far seem to suggest that breaking the query up into multiple statements like this, but i still seem to be getting this error. Anyone have an idea whats going on?

Thanks!

CodePudding user response:

As the error message says, in order to have a whereNotIn condition in you query you need to make sure that the first orderBy on that query is on the same field as that condition.

So:

FirebaseFirestore.instance
  .collection('waves')
  .where('replyTo', isEqualTo: waveId)
  .orderBy('senderId')
  .where('senderId', whereNotIn: blockerUserIds)
  .orderBy('createdAt', descending: true)
  .limit(5);

Note: this query likely required a composite index, so be sure to check the error output for a message about that and a link to where to most easily create that.

This also implies that the results will first be ordered on the value of senderId and only on createdAt for documents that have the same senderId. If that is not what you want, you'll have to re-order the documents in your application code after retrieving them.

  • Related