firebase 检查 child 是否存在

firebase check if child exists

所以我的后端使用 firebase。我的目标是将用户匹配添加到用户 ID。但是,当用户最初注册时,他们没有匹配项。我想要做的是检查 "match" child 是否存在于用户 child 中,如果不存在,则创建列表 child 并且第一个匹配项是存储。但是,如果它已经存在,则只需添加该匹配项。这是我的代码:

    public void setMatch(final String match){
    final Firebase ref = new Firebase("FIREBASEURL");
    final Firebase userRef = ref.child("Flights").child(userName);
    userRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            System.out.println("does the child exist? " + dataSnapshot.child("matches").exists());
            if(!dataSnapshot.child("matches").exists()){
                ArrayList<String> matches = new ArrayList<String>();
                matches.add(match);
                Firebase matchesRef = userRef.child("matches");
                matchesRef.setValue(matches);
                userRef.removeEventListener(this);
            }else if(dataSnapshot.child("matches").exists()){
                Map<String, Object> matches = new HashMap<>();
                matches.put("matches", match);
                userRef.child("matches").push().setValue(matches);
                userRef.removeEventListener(this);
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
}

目前,该值被添加了两次(如果字段已经 exists/its 被调用,则 else if 被调用两次,如果它没有被调用)。我不确定我做错了什么。

如果 if 块中不存在该字段,那么您似乎创建了该字段,然后测试该字段(刚创建的)是否存在,现在确实存在,所以它再次添加它。 removeEventListener 调用将删除侦听器,但不会阻止当前代码完成。

尝试:

if(!dataSnapshot.child("matches").exists()){
            ArrayList<String> matches = new ArrayList<String>();
            matches.add(match);
            Firebase matchesRef = userRef.child("matches");
            matchesRef.setValue(matches);
            userRef.removeEventListener(this);
            return; 
        }else if(dataSnapshot.child("matches").exists()){
            Map<String, Object> matches = new HashMap<>();
            matches.put("matches", match);
            userRef.child("matches").push().setValue(matches);
            userRef.removeEventListener(this);
        }

添加 return 语句应该完全符合当前调用,并且仍会按您的预期禁用侦听器。

这听起来太复杂了。在 Firebase 数据库中,通常最好尽可能地分离读取和写入操作。虽然推送 ID 是按时间顺序存储数据的好方法;如果项目有自然键,通常最好将它们存储在该键下。

例如,如果您的 String match 确实是一个 String matchId,您可以通过使用 matchId 作为键来确保每个匹配项最多出现一次。

userRef.child("matches").child(matchId).setValue(true);

这个操作是幂等的:无论你运行多久,它都会给出相同的结果。

您会注意到我没有检查 matches 是否已经存在:Firebase 数据库会自动创建存储该值所需的所有节点,并自动删除其下没有任何值的所有节点.