skip to Main Content

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

2

Answers


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

    Login or Signup to reply.
  2. If you need to make queries to find messages related to a specific user you can simply create a document for the user, with the user data such as username, email, etc, and then create a subcollection for the messages, then you won’t need to make queries.

    Also, storing user messages (assuming what you are storing is that) inside a single document is not a good practice, since it can scale up in size and reach the maximum size of a single document in firebase that is 1Mb.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search