How do I check if a firebase database value exists?

后端 未结 6 847
野趣味
野趣味 2020-11-28 05:36

I\'m using the Realtime Database with Google\'s Firebase, and I\'m trying to check if a child exists.

My database is structured as the following

- /          


        
相关标签:
6条回答
  • 2020-11-28 06:19
    users = new HashMap<>();
                    users.put("UserID", milisec);
                    users.put("UserName", username);
                    users.put("UserEmailID", email);
                    users.put("UserPhoneNumber", phoneno);
                    users.put("UserPassword", hiddenEditPassword);
                    users.put("UserDateTime", new Timestamp(new Date()));
                    users.put("UserProfileImage", " ");
    
                    FirebaseFirestore.getInstance().collection("Users").document(phoneno).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                            if (task.getResult().exists()) {
                                Toast.makeText(SignupActivity.this, "Already User", Toast.LENGTH_SHORT).show();
    
                            } else {
                                FirebaseFirestore.getInstance().collection("Users")
                                        .document(phoneno).set(users).addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        Toast.makeText(SignupActivity.this, "Registers", Toast.LENGTH_SHORT).show();
    
                                    }
                                });
                            }
                            hideProgressDialog();
                        }
                    });`
    enter code here
    
    0 讨论(0)
  • 2020-11-28 06:23

    You can check snapshot.exists value.

    NSString *roomId = @"room1";
    FIRDatabaseReference *refUniqRoom = [[[[FIRDatabase database] reference]
                                          child:@"rooms"]
                                         child:roomId];
    
    [refUniqRoom observeSingleEventOfType:FIRDataEventTypeValue
                                withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
    
        bool isExists = snapshot.exists;
        NSLog(@"%d", isExists);
    }];
    
    0 讨论(0)
  • 2020-11-28 06:25
    self.ref = FIRDatabase.database().reference()
    
       ref.child("rooms").observeSingleEvent(of: .value, with: { (snapshot) in
    
            if snapshot.hasChild("room1"){
    
                print("true rooms exist")
    
            }else{
    
                print("false room doesn't exist")
            }
    
    
        })
    
    0 讨论(0)
  • 2020-11-28 06:27

    I have some suggestions by using firebase.You check it from firebase.

    We can test for the existence of certain keys within a DataSnapshot using its exists() method:

    A DataSnapshot contains data from a Firebase database location. Any time you read data from a Firebase database, you receive the data as a DataSnapshot.

    A DataSnapshot is passed to the event callbacks you attach with on() or once(). You can extract the contents of the snapshot as a JavaScript object by calling its val() method. Alternatively, you can traverse into the snapshot by calling child() to return child snapshots (which you could then call val() on).

    A DataSnapshot is an efficiently-generated, immutable copy of the data at a database location. They cannot be modified and will never change. To modify data, you always use a Firebase reference directly.

    exists() - Returns true if this DataSnapshot contains any data. It is slightly more efficient than using snapshot.val() !== null.

    Example from firebase documentation(javascript example)

    var ref = new Firebase("https://docs-examples.firebaseio.com/samplechat/users/fred");
    ref.once("value", function(snapshot) {
      var a = snapshot.exists();
      // a === true
    
      var b = snapshot.child("rooms").exists();
      // b === true
    
      var c = snapshot.child("rooms/room1").exists();
      // c === true
    
      var d = snapshot.child("rooms/room0").exists();
      // d === false (because there is no "rooms/room0" child in the data snapshot)
    }); 
    

    Also please refer this page(already mentioned in my comment)

    Here there is an example using java.

    Firebase userRef= new Firebase(USERS_LOCATION);
    userRef.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            if (snapshot.getValue() !== null) {
                //user exists, do something
            } else {
                //user does not exist, do something else
            }
        }
        @Override
        public void onCancelled(FirebaseError arg0) {
        }
    });
    

    I hope you got an idea now.

    0 讨论(0)
  • 2020-11-28 06:31

    Use any of them So simple and easy ... Which way you like

    ValueEventListener responseListener = new ValueEventListener() {
        @Override    
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                // Do stuff        
            } else {
                // Do stuff        
            }
        }
    
        @Override    
        public void onCancelled(DatabaseError databaseError) {
    
        }
    };
    
    FirebaseUtil.getResponsesRef().child(postKey).addValueEventListener(responseListener);
    

    function go() {
      var userId = prompt('Username?', 'Guest');
      checkIfUserExists(userId);
    }
    
    var USERS_LOCATION = 'https://SampleChat.firebaseIO-demo.com/users';
    
    function userExistsCallback(userId, exists) {
      if (exists) {
        alert('user ' + userId + ' exists!');
      } else {
        alert('user ' + userId + ' does not exist!');
      }
    }
    
    // Tests to see if /users/<userId> has any data. 
    function checkIfUserExists(userId) {
      var usersRef = new Firebase(USERS_LOCATION);
      usersRef.child(userId).once('value', function(snapshot) {
        var exists = (snapshot.val() !== null);
        userExistsCallback(userId, exists);
      });
    }
    

    Firebase userRef= new Firebase(USERS_LOCATION);
    userRef.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            if (snapshot.getValue() !== null) {
                //user exists, do something
            } else {
                //user does not exist, do something else
            }
        }
        @Override
        public void onCancelled(FirebaseError arg0) {
        }
    });
    
    0 讨论(0)
  • 2020-11-28 06:39

    While the answer of @ismael33 works, it downloads all the rooms to check if room1 exists.

    The following code accomplishes the same, but then only downloads rooms/room1 to do so:

    ref = FIRDatabase.database().reference()
    
    ref.child("rooms/room1").observeSingleEvent(of: .value, with: { (snapshot) in
        if snapshot.exists(){
            print("true rooms exist")
        }else{
            print("false room doesn't exist")
        }
    }) 
    
    0 讨论(0)
提交回复
热议问题