Firestore中如何在安全规则约束下基于指定数组字段查询数据
正确的Firestore查询方式适配你的安全规则
Hey there! Let's figure out how to write the right query that works with your Firestore security rules.
First, let's recap your setup: your rule allows read access only if the authenticated user's email exists in the email array of the target document. To make a query that passes this rule and returns the correct data, you need to align your query logic with the rule's requirement.
Key Points to Note
- Firestore has a dedicated operator for checking if an array contains a specific value:
array-contains. This is exactly what you need here, since youremailfield is an array. - Firestore's security rules enforce that every document your query could potentially return must satisfy the rule. That means you can't skip adding the
emailcondition to your query—otherwise, the rule will block the request, as it can't guarantee all results meet the access requirement.
Correct Query Code
Here's how to structure your query properly (note I fixed the collection name inconsistency between your rule and example query—make sure to use the actual collection name from your rules):
// First, ensure the user is authenticated const currentUser = firebase.auth().currentUser; if (currentUser) { const userEmail = currentUser.email; db.collection("collection") // Use the same collection name as in your security rules (you wrote "store" in your example, check which is correct!) .where("email", "array-contains", userEmail) // This matches your security rule's condition .where("id", "==", "1") // Add your additional filter here .onSnapshot(function(querySnapshot) { querySnapshot.forEach(doc => { console.log("realtime----", doc.id, doc.data()); }); }, function(error) { console.error("Error fetching snapshot:", error); }); } else { console.log("User is not logged in—authentication required for this query."); }
Additional Tips
- Collection Name Consistency: Your security rules target
/collection/{documentId}, but your example query usesdb.collection("store"). Double-check which collection name is correct and make sure they match—otherwise, the rules won't apply to your query. - Composite Index: If you're combining multiple
whereclauses (likeemail array-containsandid ==), Firestore will likely ask you to create a composite index. When you run the query, you'll see an error message with a direct link to create the required index in the Firebase Console—just follow that link and it's done in a click.
内容的提问来源于stack exchange,提问作者Hua Mai
相关产品推荐
相关产品推荐

