[英]how to pull id from push() firebase?
Can someone please explain me why firebase unique id starting with '-' ? 有人可以解释一下为什么Firebase唯一ID以'-'开头吗?
I have two questions: 我有两个问题:
How can i get the id from push, if there is any return to this request? 如果对此请求有任何回报,我如何从推入中获取ID?
firebase.database().ref('carts/-KJp9LdQkEN1DtuCLjfP/pro').push({
name:name,
amount:am
});
On this part i'm trying to handle the callback snapshot. 在这一部分,我试图处理回调快照。 All my attempt to extract the data from this json have failed.
我从此json提取数据的所有尝试均失败了。
JSON.parse(data) == error
snapshot.key(); == error
data[0] == error
firebase.database().ref('carts/').on('value', function(snapshot) {
var data = snapshot.val();
console.log(data);
});
These keys (often called "push ids") start with a -
because that is the first character in the dictionary used to generate them. 这些键(通常称为“ push id”)以
-
开头,因为这是字典中用于生成它们的第一个字符。 See this blog post explaining how they are generated . 请参阅此博客文章,解释它们是如何生成的 。
If you are trying to get the push id of a item you're adding, you can do that like this: 如果您尝试获取要添加的项目的推送ID,则可以执行以下操作:
var newRef = firebase.database().ref('carts/-KJp9LdQkEN1DtuCLjfP/pro').push();
console.log(newRef.key);
newRef.set({
name:name,
amount:am
});
If you want to determine the key of an item in a listener, you can do that like this: 如果要确定侦听器中某项的键,可以执行以下操作:
firebase.database().ref('carts/').on('value', function(snapshot) {
console.log(snapshot.key); // carts
var data = snapshot.val();
console.log(data);
});
More likely if you're listening for children, you'd get the key with this: 如果您正在听孩子的话,您很有可能会得到以下提示:
firebase.database().ref('carts/').on('child_added', function(snapshot) {
console.log(snapshot.key); // -KJ....
var data = snapshot.val();
console.log(data);
});
Or like this: 或像这样:
firebase.database().ref('carts/').on('value', function(snapshot) {
snapshot.forEach(function(cartSnapshot) {
console.log(cartSnapshot.key); // -KJ....
console.log(cartSnapshot.val());
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.