Home > OS >  Firebase query filter
Firebase query filter

Time:12-19

I am using react with firebase. a very simple auth login (firebase/firestore). In the DB i have one collection named "posts". I am trying to get the list of all the "username" form the post db while removing duplicates (duplicated username). Is there a way to add "filter" to the firebase query directly? else... I am trying to write a filter before using a map but i do not know how to refer to the username in the filter.

const Profiles = () => {
  const [profiles, setProfiles] = useState();

  const getProfiles = async () => {
    const collectionRef = collection(db, 'posts');
    const q = query(collectionRef, orderBy('username'));
    const unsubscribe = onSnapshot(q, (snapshot) => {
      const result = snapshot.docs.map((doc) => ({
        ...doc.data(),
        id: doc.id,
      }));
    });

    (error) => {
      console.log(error);
    };
  };

  useEffect(() => {
    getProfiles();
  }, []);

  return (
    <div>
      {profiles
        .filter((profile) => profile.username != username???)
        .map((profile) => {
          const {username} = profile.username;
          <div key={profile.id}>{profile.username}</div>
        })}
    </div>
  );
};

export default Profiles;

CodePudding user response:

There is no option to get only distinct values in Firestore query results.

In typical NoSQL fashion that'd be something you solve by adapter your data model to your needs. So if you want to be able to get a list of unique user names, create an (typically additional) collection usernames where you store one document for each user name with that user name as the document ID. Since document IDs are unique within their collection, that by definition means there can be no duplicates. And it then becomes trivial to get just the distinct usernames by reading that collection.

  • Related