skip to Main Content

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:

enter image description here

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


  1. 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.

    Login or Signup to reply.
  2. 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);
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search