In my Firestore transaction, I am creating a new document in the accounts
collection and linking its ID to the user's accounts
. The account object being sent includes the user ID within the members
field.
db.runTransaction(transaction => {
return transaction.get(db.collection('accounts').doc())
.then(res => {
const accountId = res.id;
transaction.set(db.collection('accounts').doc(accountId), {name, numberOfEmployees, businessTypes, industry, members})
transaction.set(db.collection('users').doc(uid), {accounts: {[accountId]: true}}, {merge: true})
return accountId;
}, error => error)
})
I am relying on the behavior of .collection('accounts').doc()
without a specified path to create a new document. However, I am encountering the "Missing or insufficient permissions" error despite having set up rules:
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth.uid == userId;
}
match /accounts/{accountId} {
// allow read if user is a member or if the document does not exist
allow read : if resource.data.members[request.auth.uid] == true || !exists(/databases/{database}/documents/accounts/$(accountId));
// allow update, delete if user is a member
allow update, delete: if resource.data.members[request.auth.uid] == true;
// allow creation of any authenticated user
allow create: if request.auth != null;
}
}
}
The issue seems to be with the read
rule on /accounts/{accountId}
. Adjustments are needed to grant access to documents that have not been created yet. What modification should be made to allow this?