0

how to search/check a data in firebase realtime database before adding when the data was inserted using unique ids such as screenshot here: myfirebase data

(screenshot looks like bellow)

+users

--LMXmJKkb8khQa08zRtD

-----name : "John"

-----status : 1

--LMXmRscUZPvp00oVv5s

-----name : "Peter"

-----status : 1

Note: the app does not know or have copy of the unique ids so there is no way i can access it directly.

I want to check if the "name" is unique before adding/inserting it to the database.

here is the code i did so far (note this is in C++, you can post your answer in any language)

firebase::database::DatabaseReference userRef = database->GetReference();   
SampleValueListener* listner = new SampleValueListener();
userRef.Child("users").OrderByChild("name").EqualTo("John").AddValueListener(listner);

class SampleValueListener : public firebase::database::ValueListener {
 public:
     void OnValueChanged(
          const firebase::database::DataSnapshot& snapshot) override {
         if (snapshot.exists()) {
            printf("\nData exist");
         }
      }

    void OnCancelled(const firebase::database::Error& error_code,
    const char* error_message) override {
    printf("ERROR: SampleValueListener canceled: %d: %s", error_code,
        error_message);
   }
};

so far i am getting an error:

ERROR: SampleValueListener canceled: 10: Index not defined, add ".indexOn": "name", for path "/users", to the rules

So i need help in the following:

  1. so how do i set the indexon when i cant access directly how to access the name as it is under a uniqueid indentifier?

  2. Am I doing it the right way? (from the above code), How can i check if a "name" exist before adding a value?

user2300947
  • 450
  • 4
  • 14
  • For defining an index, see https://firebase.google.com/docs/database/security/indexing-data and https://stackoverflow.com/questions/33573615/how-to-create-an-index-on-a-child-property-of-an-array-object-in-firebase. For checking uniqueness, check https://stackoverflow.com/questions/39149216/firebase-security-rules-to-check-unique-value-of-a-child-askfirebase – Frank van Puffelen Sep 16 '18 at 17:09

1 Answers1

1

Does adding the below to your firebase rules fix the issue?

"rules": {
    "users": {
        ".indexOn": "name"
     }
 }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
sbso
  • 403
  • 4
  • 8