Below is an example of how you can update your rules so that when a user creates a new document in a subcollection (e.g. table_list) under a customer_list document, the rule verifies that the customer document’s create_by field indeed points to the current user. In this example, we compare the parent document’s create_by.path (a string such as “/users/abcd”) with the constructed user path.
Make sure that in your Firestore documents the create_by field is stored as a DocumentReference so that its path is, for example, "/users/abcd". Then you can use a rule like this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Users collection rules (for reference)
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
}
// Customer documents and their subcollections
match /customer_list/{customerId} {
// Allow anyone to create/read the customer document itself;
// adjust as needed.
allow create, read: if true;
// Subcollection for table_list (make sure the collection name is accurate)
match /table_list/{tableId} {
// Allow create if the current user is the owner of the customer_list document,
// that is, if the create_by field in the parent document points to their user doc.
allow create: if request.auth != null &&
get(/databases/$(database)/documents/customer_list/$(customerId))
.data.create_by.path == '/users/' + request.auth.uid;
// Optionally, you can add read and update rules as needed
allow read: if true;
// For update or delete, you might want similar checks.
}
}
}
}
Tips and Common Pitfalls
-
Parent Document Lookup:
In the create rule for table_list, we use get() to look up the parent customer_list document and its create_by field. Make sure that the customer_list document exists before the table_list document is created.
-
DocumentReference Comparison:
If you’d prefer to compare the user id directly and the DocumentReference supports the .id property, you could try the following in your rule:
get(/databases/$(database)/documents/customer_list/$(customerId))
.data.create_by.id == request.auth.uid
However, comparing the .path property is more explicit because you know exactly what the expected path should be.
-
Collection Name Consistency:
Verify that your collection names match exactly. In your question you mention table_list but your original rule example used food_list.
Updating your security rules as shown above should allow the current user (matching the create_by field on the customer document) to create new documents in the table_list subcollection.