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);
}
}
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.
class UsersService {
async getUsers(): Promise<IUser[] | undefined> {
const userUid = auth.currentUser?.uid;
const q = query(
collection(db, "users"),
orderBy("name")
);
const querySnapshot = await getDocs(q);
// Filter out the current user after fetching the data
return querySnapshot.docs
.map((doc) => doc.data() as IUser)
.filter((user) => user.uid !== userUid);
}
}