Bartek Pacia
Bartek Pacia

Reputation: 1726

Firestore: sort by Firestore Timestamp causes UnhandledPromiseRejectionWarning

I try to get documents from my Firestore and sort them by their timestamp. The Timestamp is actually in the "firebase format" (see below)

My date format

Code

I tried using this code

const querySnapshot = await db
    .collection("placeVisits")
    .where("placeId", "==", req.params.placeId)
    .orderBy("time", "desc")
    .get();

but it produces error: (node:8356) UnhandledPromiseRejectionWarning: Error: 9 FAILED_PRECONDITION: The query requires an index. You can create it here: https://console.firebase.google.com/...

However, this works fine (but doesn't sort, of course)

const querySnapshot = await db
    .collection("placeVisits")
    .where("placeId", "==", req.params.placeId)
    .get();

I've no idea how to fix this or why it happens. Is it because Firestore Snapshots aren't sortable or something?

Upvotes: 0

Views: 282

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600126

The query on .where("placeId", "==", req.params.placeId).orderBy("time", "desc") requires a composite index, which is not automatically created by Firestore.

The error message contains a link. If you click the link it takes you to a page in the Firebase console to create the necessary index. All fields should be pre-populated there, so you should just have to click a button.

Upvotes: 1

Related Questions