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));
2
Answers
You would need to pass the full object with
array-contains
for the query to work for example:The
==
query is used for properties, so if you have auserId
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 themessageObj
as fields in that document.You can check more here:
https://firebase.google.com/docs/firestore/query-data/queries
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.