如何检查一个基本数据库值是否存在?

时间:2022-04-13 20:17:32

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

我正在使用谷歌的Firebase的实时数据库,并试图检查是否存在子数据库。

My database is structured as the following

我的数据库结构如下

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

I would like to check if room1 exists. I have tried the following:

我想确认一下房间1是否存在。我试过以下方法:

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

In accessing snap.value it returns a JSON of the properties of that room, but how would I check if the room (/rooms/room1/) is there to begin with?

在访问。它返回的是该房间属性的JSON,但是我如何检查房间(/房间/房间1/)是否开始?

Comment if any clarification is needed

如果需要澄清,请发表意见

5 个解决方案

#1


53  

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


    })

#2


7  

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

我对使用firebase有一些建议。你从消防队检查。

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

我们可以使用DataSnapshot的exist()方法来测试某个键是否存在:

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.

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).

DataSnapshot被传递给您附加到on()或once()的事件回调。通过调用它的val()方法,可以将快照的内容作为JavaScript对象提取。或者,您可以通过调用child()来访问快照,以返回子快照(然后可以调用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.

DataSnapshot是数据库位置上高效生成的、不可变的数据副本。它们不能修改,也永远不会改变。要修改数据,您总是直接使用一个Firebase引用。

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

exist()——如果这个数据快照包含任何数据,则返回true。它比使用snapshot.val() != null稍微高效一些。

Example from firebase documentation(javascript example)

来自firebase文档的示例(javascript示例)

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.

这里有一个使用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.

我希望你现在有个主意。

#3


6  

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

虽然@ismael33的答案是有效的,但是它下载了所有的房间来检查房间1是否存在。

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

下面的代码实现了同样的功能,但是只有下载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")
    }
}) 

#4


1  

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

#5


0  

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

#1


53  

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


    })

#2


7  

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

我对使用firebase有一些建议。你从消防队检查。

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

我们可以使用DataSnapshot的exist()方法来测试某个键是否存在:

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.

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).

DataSnapshot被传递给您附加到on()或once()的事件回调。通过调用它的val()方法,可以将快照的内容作为JavaScript对象提取。或者,您可以通过调用child()来访问快照,以返回子快照(然后可以调用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.

DataSnapshot是数据库位置上高效生成的、不可变的数据副本。它们不能修改,也永远不会改变。要修改数据,您总是直接使用一个Firebase引用。

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

exist()——如果这个数据快照包含任何数据,则返回true。它比使用snapshot.val() != null稍微高效一些。

Example from firebase documentation(javascript example)

来自firebase文档的示例(javascript示例)

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.

这里有一个使用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.

我希望你现在有个主意。

#3


6  

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

虽然@ismael33的答案是有效的,但是它下载了所有的房间来检查房间1是否存在。

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

下面的代码实现了同样的功能,但是只有下载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")
    }
}) 

#4


1  

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

#5


0  

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