Firebase update fields only when its empty
Firebase update fields only when its empty
I have a data set on firebase real time database like this.
Users
---Match
------User1
mId:"12345"
xId:""
------User2
mId:"54321"
xId:""
Basically developing a multi player matching functionality here using android application.Assuming user 1 matched with user 2. User1 will update his own xId value with user2 mId value and user2 will update his own xId value with mId value of user1.
This works fine if there are two users. Both connects to each other and works well. Issue comes when 3 users come at the same time. User1 writes to user2 and user2 writes to user3 and creates inconsistent data set.
I want to lock a value once it is changed or we can say a simple rule like.
update user1 only : if(user1.xid=="")
update user2 only : if(user2.xid=="")
Is it possible using firebase security rule?
1 Answer
1
To only allow writing new data (so never overwrite or delete existing data), you'll want this rule:
"rules":
"Users":
"Match":
"uid":
".validate": "!data.child('xid').exists() && newData.child('xid').exists()"
For more elaborate information check out the Firebase documentation for security rules, specifically the section on New vs. Existing Data.
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy