React Native中Firestore多值数组查询与办公集合检索问题
First, let's fix a key detail in your current setup: using '==' with an array field like userIds won't work when you're trying to find offices that include the user. Firestore has a dedicated operator for array membership—array-contains—that we'll use for your first requirement.
1. Fetch All Offices the User Belongs To
To retrieve every office where the user's ID exists in the userIds array, update your firestoreConnect configuration to use the array-contains operator:
import { firestoreConnect } from 'react-redux-firebase'; // Wrap your component with the corrected firestoreConnect const ConnectedComponent = firestoreConnect(props => [ { collection: 'office', where: ['userIds', 'array-contains', props.id], // Use array-contains for array membership checks storeAs: 'userOffices' // Optional: Name the collection in your Redux store for clarity } ])(YourComponent);
Quick Explanation:
array-containschecks if theuserIdsarray includes the user's ID (props.id), which is exactly what you need to find all offices the user is part of.- Use
storeAsto avoid overwriting other collections in your Redux store—you can then access the offices viaprops.firestore.ordered.userOffices(for ordered results) orprops.firestore.data.userOffices.
2. Retrieve Offices by officeId
Depending on your use case, there are two straightforward ways to fetch offices by their officeId:
Option A: Fetch a Single Office by Exact ID
If you know the specific officeId you want to retrieve, target the document directly:
const ConnectedComponent = firestoreConnect(props => { const { targetOfficeId } = props; // Pass the desired office ID as a prop return [ { collection: 'office', doc: targetOfficeId, // Directly reference the document by its ID storeAs: 'targetOffice' } ]; })(YourComponent);
Access the office data later via props.firestore.data.targetOffice.
Option B: Query Multiple Offices by officeId
If you need to filter a list of offices (e.g., searching for a specific ID), use a where clause with == (since officeId is a string field):
const ConnectedComponent = firestoreConnect(props => { const { searchOfficeId } = props; // The office ID to search for return [ { collection: 'office', where: ['officeId', '==', searchOfficeId], storeAs: 'searchedOffices' } ]; })(YourComponent);
Note:
Your example shows multiple documents sharing the same officeId (like two entries for OF005). If you intended officeId to be unique, consider restructuring your collection to use officeId as the document ID instead of a field. This makes fetching single offices more efficient and eliminates duplicate IDs.
内容的提问来源于stack exchange,提问作者Lakshan

