Using Firebase Firestore to fetch an array field from a particular document and then leveraging those array values for mapping other documents

In my database, I have user and group collections. Each document in the user collection corresponds to a user UID and contains an array field called "userGroups" which lists the groups that user belongs to, with each group being identified by the group's document ID in the group collection.

I've successfully retrieved the userGroups array for the current user and stored it in groupRef (refer to code below). Now, my goal is to map these values to the groups collection and fetch only those documents that are included in the groupRef array. Essentially, I want to display in the UI only the groups that the current user is a member of.

user collection group collection

const [groupsList, setGroupList] = useState([]);
const [groupRef, setGroupRef] = useState([]);
const [track, setTrack] = useState('')

const handleSubmit = () => {
    setTrack('start')
    fire.firestore().collection('users').doc(fire.auth().currentUser.uid).get().then((value) => {
        console.log("userGroups  " + value.data().userGroups)   // this returns an object
        setGroupRef([value.data().userGroups])
    })
} 

useEffect(() => {
    handleSubmit()
}, [track])

console.log("sample list   " + groupRef)

    fire.firestore().collection('groups').onSnapshot(snapshot => (
        setGroupList(snapshot.docs.map(doc => doc.data()))
    ))

^ This code snippet retrieves all documents from the groups collection. Any suggestions on how I can filter and retrieve only the ones where the current user is a member? Your assistance would be greatly appreciated as I've been struggling with this issue for a while. I'm also new to working with Firebase.

Answer №1

Thanks to the guidance of @DougStevenson, I discovered the power of using array-contains when querying data. The code snippet below provided the perfect solution to my issue. Implementing this method proved to be a more concise and efficient approach compared to my initial solution.

fire.firestore().collection('groups').where("groupMembers", "array-contains", fire.auth().currentUser.uid).onSnapshot(snapshot => ( setGroupList(snapshot.docs.map(doc => doc.data()))
)) 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Invoke the ngrx component store's Effect in a synchronous manner

In the ComponentStore of ngrx, we have two effects. readonly startAndUpdateProgress = this.effect<void>( (trigger$) => trigger$.pipe( exhaustMap(() => this.numbersObservable.pipe( tapResponse({ next: (p ...

JavaScript Integration for Microsoft Dynamics NAV

I have developed a JavaScript Addin for Microsoft Dynamics Nav 2013. The Addin functions properly when used on the same machine as Navision. However, when I replace "localhost" with the machine's name, the Addin stops working. Below is the script I am ...

Conceal any elements designated by a particular class and reveal them based on their corresponding ID

I have utilized jQuery's hide() function to initially hide all elements of a specific class when the page loads. My goal is to make individual elements visible again based on their unique IDs when a corresponding link is clicked. In total, there are ...

Establish a route nickname for files outside the project directory

I'm currently tackling a project that is divided into multiple angular projects. Within these projects, there are some services that are shared. Is there a way for me to incorporate these services into my project without encountering errors? /root / ...

What is the method for calling a JavaScript function from one file to another within a Node.js environment?

Just starting out with JavaScript and exploring the idea of breaking the code into multiple modules. While working with nodejs, I've encountered an issue where it's complaining about pathChecker not being defined. Any insights on how to resolve t ...

When the return false statement is included, the form fails to submit and instead refreshes on the current page

I recently discussed an issue regarding triggering a dialog box before confirming a submit action. Unfortunately, after implementing this, the document no longer submits when expected. Instead, it just remains on the same page with the same settings. I h ...

Remove outdated cards from a React array

I am facing a complicated situation and require some assistance. Below is the code snippet: The function provided below is used to determine if a credit card has expired or not. It returns true if the card is expired and false if it's valid. const i ...

Guide on transferring an HTML variable to a PHP script through AJAX

I am currently working on my website where I aim to create a random code that will be passed onto a PHP file for future retrieval. However, the code seems to be malfunctioning. Take a look at the code: Javascript/HTML: function init() { var code ...

Transform a text with HTML tags into sentences while preserving the separators in Javascript

Here is a unique string with some embedded HTML code: This is the first sentence. In the second sentence, there is a <a href="http://google.com">Google</a> link! The third sentence may have an image like <img src="http://link.to.image.com/h ...

Troubleshooting: Issue with Dependency Injection functionality in Angular 2 starter project

I’ve encountered a strange error whenever I attempt to inject any dependency TypeError: Cannot set property 'stack' of undefined at NoProviderError.set [as stack] (errors.js:64) at assignAll (zone.js:704) at NoProviderError.ZoneAwareError (zon ...

The JavaScript indexOf method in an unordered list incorrectly returns the index of a specific event

Looking to retrieve the index number of an 'li' element within a 'ul' from the HTML structure. I attempted to convert the 'ul' into a list and access its children using: [...ul.children] However, upon targeting any of the chi ...

Saving information from JSON data obtained through the Google People API

My server is connected to the Google People API to receive contact information, and the data object I receive has a specific structure: { connections: [ { resourceName: 'people/c3904925882068251400', etag: '%EgYBAgkLNy4aDQECAwQFBgcICQoLD ...

Quick shorthand if statement that will constantly return true

I am dealing with a dropdown menu that displays different groups. Each group has a property (boolean) indicating whether the owner is a user or another group. If the group's owner is a user, I obtain the ownerID of the group and compare it with an ar ...

NextJs getStaticPaths function is failing to render the correct page, resulting in a 404 error message being displayed

Hey there, I'm in a bit of a pickle as I've never used 'getStaticPaths' before and it's crucial for my current project! I followed the example code from NextJs's documentation on 'getStaticPaths', but when I try to ...

Exporting methods/functions in React Native

import { width as responsiveHeight } from "react-native-responsive-dimensions"; I am trying to export responsiveHeight with the name width. Can someone please guide me on the correct way to do this? The current approach is not yielding any results. ...

Is it possible to create a bot that's capable of "hosting events" using Discord.js?

I am searching for a solution to host "events" using Discord.js. After some research, I stumbled upon this. Although it seems to be exactly what I am looking for, the website does not provide any code examples to help me try and replicate its functionali ...

The 'onClick' prop is required but was not specified // Error: Unable to access the 'bind' property

I am having trouble passing the 'handleWordClick' function to a component as I keep getting an error stating that the proptype was not specified. Additionally, when attempting to pass the prop with .bind 'this.handleWordClick.bind(this)&ap ...

Enter information into the TextArea and jQuery dialog

I require assistance in populating a textarea with data obtained from querying a database. I have a jQuery dialog that contains another dialog, inside of which is a textarea. Here is some pseudocode: <MODAL> <modalB> <TextArea>s ...

Use JavaScript to load a component or call a method only when it is necessary

Looking for a solution to eliminate script tags from my HTML views. For instance: (A view containing a script tag) <script type="text/javascript"> $jQuery().ready(function() { call.a.method(); } </script> I want to remove th ...

What is the best way to delete an input field and completely erase the data within it?

I'm working on a button that should add and remove input fields and clear the data inside those fields when removed. However, I'm facing an issue where the data still remains even after removing the input. How can I resolve this problem? Below i ...