0

我正在尝试检查是否使用了 Firebase 文档中给出的示例中的用户名:


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

但是我引用的数据位于我在引用时遇到问题的数据层中:

firebaseio.com/{userID}/primary/{username}

151 (用户ID) | |> 初级 | |> 用户名:用户名

我想检查用户 ID 子项下主树下的用户名字段......有什么建议吗?

4

1 回答 1

1

有点不清楚您的数据结构是什么;见我上面的评论。对您的数据做出几个假设,它看起来像这样:

{151}/primary/username/{kato}

大括号中的部分是变量位,其余部分是固定键,那么您只需按如下方式更改路径:

// in checkIfUserExists
usersRef.child(userId).child('primary/username').on('value', ...)

如果您没有用户 ID,那么您可以迭代所有用户并检查名称:

usersRef.once('value', function(ss) {
    ss.forEach(function(childSnapshot) {
       var userID = childSnapshot.name();
       childSnapshot.ref().child('primary/username').once('value', function(ss) {
           var userName = ss.val();
           /* do something with name and ID here */
       });
    });
});

或者,如果您怀疑您的用户列表将非常庞大(数千),您可能希望将用户名索引到单独路径中的 id 并避免任何迭代:

userList/{username}/{userID}

然后您可以按如下方式使用:

 userListRef.child(username).once('value', function(ss) {
    var userID = ss.val();
    if( userID !== null ) {
        /* user exists and we have the name and id now */
    }
 });
于 2013-02-16T15:30:54.217 回答