在JavaScript中获取子节点的密钥Firebase
问题描述:
我试图从子节点数据获取密钥。在JavaScript中获取子节点的密钥Firebase
$(document).on('click', '#enter', getName);
function getName() {
name = $('#user').val().trim();
database.ref('players/' + name).push({
name: name
})
}
database.ref('players/' + name).child(name).on("child_added",
function(childSnapshot){
var childKey = childSnapshot.key;
var childData = childSnapshot.val;
console.log('key', childKey)
console.log('data', childData)
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
})
})
在快照功能,当我控制台日志childKey
,它显示的关键是用户,这是我在ref('players/' + name)
创建的路径名。但我需要嵌套在name
节点内的节点的密钥。我的childSnapshot
函数中出现错误,说明.child(name) is an invalid path
。还说,
路径必须为非空字符串,不能包含 “”, “#”, “$”, “[” 或 “]”
目前我创建数据到火力地堡它看起来像这样:
-players
-Johnson
-KWH4mjWbOuptod_vV1o
name: "ajks"
我需要得到johnson
下键,该字母和数字的长字符串,所以我可以引用特定节点,并添加数据,修改数据,或如更新数据名字。
答
尝试这种方式
var fb_ref= firebase.database().ref('players/' + name)
fb_ref.push({
name: name
})
fb_ref.on('child_added', function (data) {
console.log(data.key);
});
或
fb_ref.push({
name: name
}).then(function(fb_ref){
console.log(fb_ref.key);
})
保持一件事记住,如果你使用上面3.X版本火力运用手段的“钥匙”,如果你的版本较低超过3 .x表示使用像这样的“key()”
[在Firebase中使用push()时可能有重复()如何拉取唯一ID](http://stackoverflow.com/questions/16637035/in-firebase-采用快插如何时,-DO-I-拉的唯一-ID) – cartant