2013-02-16 91 views
0

我試圖來檢查用戶名用作在火力地堡文檔中給出的示例:查找數據火力地堡


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下的主樹下的用戶名字段...任何建議?

+0

嗨吉姆!我對你的結構有點困惑。如果我的用戶ID是151,我的名字是「kato」,那麼路徑中的數據是'151/primary/kato/kato'?或者在你的例子中是{用戶名}錯誤? – Kato 2013-02-16 15:26:34

回答

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

或者,如果你懷疑你的用戶列表將是ludicro usly龐大(幾千),您可能需要用戶名指標到IDS在一個單獨的路徑,並避免任何重複:

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 */ 
    } 
}); 
+0

對不起 - 我的意思是{151}/primary/username/{kato} ...在你給出的解決方案中,因爲我從來沒有將用戶名151命名爲151並且從不提供用戶ID,它將如何否循環遍歷所有用戶ID? 這是用戶名,我試圖比較不是userIDs? – 2013-02-16 22:17:49

+0

查看我的更新。我希望他們幫助:) – Kato 2013-02-16 22:34:48

+0

感謝它確實幫助 - 下面是塵埃落定時的外觀:var userRef = new Firebase('https://j2000.firebaseio.com/users/'); var usernameRef = userRef.on ('child_added',function(userSnapshot){var userData = userSnapshot.val(); if(userData.primary.username === newusername){exists = newusername; userExistsCallback(exists);} else {exists = null; userExistsCallback (exists);} \t}); } – 2013-02-18 19:55:53