Search code examples
reactjsfirebasegoogle-cloud-firestore

how to get specific object from array in firestore using reactjs


I can't get spefic object out of array that includes many objects. It's "messages" array that containes objects.

I used a method below but it returned nothing.

const [userId, setUserId] = useState();

const fetch = async () => {
const searcheQuery = query( collection(db,'chats'), where('id','==',userId));
 const querySnapshot = await getDocs(searcheQuery);
 querySnapshot.forEach((doc) => { console.log( doc.data() ) })

}

I also used 'array-contains' instead of '==' but results are the same.

 const searcheQuery = query( collection(db,'chats'), where('messages','array-contains',userId));

enter image description here


Solution

  • You would need to pass the full object with array-contains for the query to work for example:

    const messageObj = {
       date: "June 9 2024",
       id: "user-id"
    }
    const searchQuery = query( collection(db,'chats'), where('messages','array-contains',messageObj));
    

    The == query is used for properties, so if you have a userId property inside your document, that query would work. To make the query easier because ofcourse you won't have the complete object, best thing is to add a subcollection with the messageObj as fields in that document.

    You can check more here:

    https://firebase.google.com/docs/firestore/query-data/queries