mobizt / Firebase-ESP32

[DEPRECATED]🔥 Firebase RTDB Arduino Library for ESP32. The complete, fast, secured and reliable Firebase Arduino client library that supports CRUD (create, read, update, delete) and Stream operations.
MIT License
415 stars 118 forks source link

How should I check if a object exists before saving it? #122

Closed maylortaylor closed 3 years ago

maylortaylor commented 3 years ago

I am trying to get a simple user creation logic flow but can't quite seem to get the "does user exist" code to work correctly.

  String path = "users/" + String(WiFi.macAddress());
  FirebaseJson userJson;
  userJson.set("name", "New User");
  userJson.set("/createdDate/.sv", "timestamp");

  if (Firebase.get(firebaseData, path)) {
    if (Firebase.set(firebaseData, path, userJson)) {
      Serial.println("--------FB---USER CREATED .set() ----- ");
      Serial.println(firebaseData.dataPath());
      Serial.println(firebaseData.pushName());
      Serial.println(firebaseData.dataPath() + "/"+ firebaseData.pushName());

      printFirebaseResult(firebaseData);
      printFirebaseError();

      globalUser.id = firebaseData.pushName();
      globalUser.wifiName = globals.ssid;
      globalUser.timezone = globals.timeZone;
      globalUser.zipcode = weatherSettings.zipCode;

      globalUser.updateInitial = 0;

    } else {
      Serial.println(firebaseData.errorReason());
    }
  } else {
      Serial.println(firebaseData.errorReason());
  }

I am doing a Firebase.get() to see if the path exists. I thought this function returns true only if it has a 200 Response and it finds something.

I've tested this multiple times and It will continuously keep creating this user (updating that createDate variable I made). Am I doing this wrong?

I just want to create the user one time and then on boot of the ESP32, I can just check "does that user/object exist", if yes then don't create a user again.

mobizt commented 3 years ago

If you want to check the node path existent, please use pathExist function.

if(Firebase.pathExist(firebaseData, "path to check"))
{
  //node found
}
maylortaylor commented 3 years ago

I tried this but I get a compilation error. I confirmed I have version 3.8.9 of the Firebase ESP32 Client by Mobizt

error: 'class FirebaseESP32' has no member named 'pathExists'
   if (Firebase.pathExists(firebaseData, path)) {
mobizt commented 3 years ago

Typo in your command pathExist not pathExists. https://github.com/mobizt/Firebase-ESP32/tree/master/src#determine-whether-defined-database-path-exists-or-not