In my app I want to get users data from Firestore in alphabetical order by name so I decided to use orderBy for that, but receive undefined.
Firestore:
Service:
class UsersService {
async getUsers(): Promise<IUser[] | undefined> {
const userUid = auth.currentUser?.uid;
const q = query(
collection(db, "users"),
where("uid", "!=", userUid),
orderBy("name")
);
const querySnapshot = await getDocs(q);
return querySnapshot.docs.map((doc) => doc.data() as IUser);
}
}
2
Answers
This typically means that you’re missing a composite index that is required for the query.
The easiest way to create the index is to catch and log the exception that the SDK gives you, and then click the link in there. That’ll take you to a page in the Firestore console with all necessary details pre-populated.
The code you’ve provided has a logical issue when constructing the Firestore query. Specifically, you cannot use the where clause with a "!=" (not equal) operator in conjunction with orderBy on a different field unless the same field is used in both the where and orderBy clauses.