AhabLives
AhabLives

Reputation: 1468

Firestore query orderBy not working?

FutureBuilder with a Firestore query on a field of Type timestamp comes back with no data in snapshot. However, the same query without the orderBy works just fine.
What am I missing ? Thanks for the help.

// Working code
future: Firestore.instance.collection('messages').where('toid',isEqualTo: _emailID).getDocuments(),
builder: (context, snapshot) ...

// Not Working - returns to if(!snapshot.hasData)
future: Firestore.instance.collection('messages').where('toid',isEqualTo: _emailID).orderBy('_timeStampUTC', descending: true).getDocuments(),
builder: (context, snapshot) ...

enter image description here

Upvotes: 5

Views: 17379

Answers (5)

Nik
Nik

Reputation: 2060

For those who are still facing issue and don't know how to add indexes

Click on Add Index from Firebase console: Cloud Firestore indexes section: You need to add collection id, fields and query scope and create Index. It will take some times to build index.

enter image description here

After adding index on fields you will get below with status enabled enter image description here

Upvotes: 3

Ajeet Kumar Sah
Ajeet Kumar Sah

Reputation: 11

write your query:-

Firestore.instance.collection('messages').where('toid',isEqualTo: _emailID).orderBy('_timeStampUTC', descending: true).getDocuments()

after this, in your log, a link will be generated. it will soething like this https://console.firebase.google.com/v1/r/project............ follow that link to create index for your query after creating the index reload your app and now you will be able to fetch all your collections. :)

Upvotes: 0

Rodrigo Mata
Rodrigo Mata

Reputation: 1859

I think you are missing a ' here '_timeStampUTC, so it should be:

 orderBy('_timeStampUTC', descending: true)

EDIT:

Also, you need to be sure to create an index for toid and other for _timeStampUTC, this is done when you try to order by a property that is not in you the where of the query.

Upvotes: 10

Rohit Maurya
Rohit Maurya

Reputation: 750

Use @ServerTimestamp annotation for _timeStampUTC and try to to orderBy query

To make Firestore automatically generate Timestamp values when we upload data to the database, we must use the annotation @ServerTimestamp and set the value to null.

Upvotes: 1

blaneyneil
blaneyneil

Reputation: 3222

yep, it's just missing an index. if you're using firestore.indexes.json then add this:

{
  "collectionId": "messages",
  "fields": [
    { "fieldPath": "toid", "mode": "ASCENDING" },
    { "fieldPath": "_timeStampUTC", "mode": "DESCENDING" }
  ]
}

Upvotes: 0

Related Questions