0

This is my database structure for the Users.

This is my database structure

As you can see in the picture, there are 2 same Identification number are registered successfully.

How can I prevent the "ICNumber"(Identification Number) to be registered more than once?

This is the rule in my RealTime Database:

This is the rule in my RealTime Database

I tried putting this piece of code but it doesn't seem to work. Is there any way I can do the prevention in my Javascript or any correct way in my Firebase Rule?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Dreammmm
  • 45
  • 5
  • There is no reliable way to prevent duplicate **values** in a JSON structure like the one you have now. It would require that the security rules scan across all nodes, which just doesn't scale. The only way to ensure something is unique in Firebase, is to use those values as the **keys** in the JSON. See https://stackoverflow.com/q/25294478, https://stackoverflow.com/a/57616541, https://stackoverflow.com/a/41113997, and https://stackoverflow.com/a/46056547 – Frank van Puffelen Mar 30 '20 at 14:57
  • Understood. The links does helps a lot! Thanks ! @FrankvanPuffelen – Dreammmm Mar 31 '20 at 07:29

1 Answers1

1

In your code, you can do the following:

// Get a reference to the database service
var database = firebase.database();
var dataRetrieved = database.ref('users').child(userId).orderByChild("ICNumber").equalTo("000326141809");
dataRetrieved.on('value', function(snapshot) {
  if(snapshot.exists()){
     // do the required
   }
});

You can use a query to check if you have an ICNumber equal to 000326141809 and then use the method exists() to check if it is already in the database

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134
  • Thank you so much! Your code works, it detects whether or not the value is already in the database. However, the code still runs my signup() function. Do you have any workaround for this? I've tried: break, return, and preventDefault statements, but they don't seem to work – Dreammmm Mar 30 '20 at 15:37
  • Just write the signup inside the else and use once instead of on – Peter Haddad Mar 30 '20 at 16:41
  • Aight man understood! Thanks for the help! – Dreammmm Mar 31 '20 at 07:30