如何检查 firebase 数据库值是否存在?

How do I check if a firebase database value exists?

我将实时数据库与 Google 的 Firebase 一起使用,我正在尝试检查子项是否存在。

我的数据库结构如下

- / (root)
-   /users/
–-    /james/
--    /jake/
-   /rooms/
--    /room1/
---      (room 1 properties)
--    /room2/
---      (room 2 properties)

我想检查房间 1 是否存在。 我尝试了以下方法:

let roomName:String = "room1"
roomsDB.child(roomName).observeSingleEventOfType(.Value) { 
(snap:FIRDataSnapshot) in
    let roomExists:Bool = snap.value != nil ? "TAKEN" : "NOT TAKEN"
 }

在访问 snap.value 时,它 returns 那个房间的 JSON 属性,但是我如何检查房间 (/rooms/room1/) 是否在那里开始与?

如果需要任何说明,请发表评论

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")
        }


    })

我有一些建议,可以使用 firebase.You 从 firebase 中查看。

我们可以使用 exists() 方法测试 DataSnapshot 中某些键的存在:

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 如果此 DataSnapshot 包含任何数据,则为真。它比使用快照更有效。val() !== null.

firebase 文档中的示例(java脚本示例)

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)
}); 

另请参考此page(我的评论中已提及)

这里有一个使用 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) {
    }
});

我希望你现在有想法了。

您可以检查 snapshot.exists 值。

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);
}];

使用它们中的任何一个如此简单和容易...... 你喜欢哪种方式

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) {
    }
});

工作时,它会下载所有 rooms 以检查 room1 是否存在。

以下代码完成相同的操作,但仅下载 rooms/room1 即可:

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")
    }
}) 
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