jQuery 在 Firebase 中使用 push() 如何提取唯一 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16637035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Firebase when using push() How do I pull the unique ID
提问by Front_End_Dev
I'm attempting to add/remove entries from a Firebase database. I want to list them in a table to be added/modified/removed (front end) but I need a way to uniquely identify each entry in order to modify/remove. Firebase adds a unique identifier by default when using push(), but I didn't see anything referencing how to select this unique identifier in the API documentation. Can this even be done? Should I be using set() instead so I'm creating the unique ID?
我正在尝试从 Firebase 数据库中添加/删除条目。我想将它们列在要添加/修改/删除(前端)的表中,但我需要一种方法来唯一标识每个条目以便修改/删除。Firebase 在使用 push() 时默认添加一个唯一标识符,但我在 API 文档中没有看到任何关于如何选择这个唯一标识符的内容。这甚至可以做到吗?我应该使用 set() 来创建唯一 ID 吗?
I've put this quick example together using their tutorial:
我已经使用他们的教程将这个快速示例放在一起:
<div id='messagesDiv'></div>
<input type='text' class="td-field" id='nameInput' placeholder='Name'>
<input type='text' class="td-field" id='messageInput' placeholder='Message'>
<input type='text' class="td-field" id='categoryInput' placeholder='Category'>
<input type='text' class="td-field" id='enabledInput' placeholder='Enabled'>
<input type='text' class="td-field" id='approvedInput' placeholder='Approved'>
<input type='Button' class="td-field" id='Submit' Value="Revove" onclick="msgRef.remove()">
<script>
var myDataRef = new Firebase('https://unique.firebase.com/');
$('.td-field').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#nameInput').val();
var text = $('#messageInput').val();
var category = $('#categoryInput').val();
var enabled = $('#enabledInput').val();
var approved = $('#approvedInput').val();
myDataRef.push({name: name, text: text, category: category, enabled: enabled, approved: approved });
$('#messageInput').val('');
}
});
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text, message.category, message.enabled, message.approved);
});
function displayChatMessage(name, text, category, enabled, approved, ) {
$('<div/>').text(text).prepend($('<em/>').text(name+' : '+category +' : '+enabled +' : '+approved+ ' : ' )).appendTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>
Now lets assume I have three rows of data:
现在让我们假设我有三行数据:
fred : 1 : 1 : 1 : test message 1
fred : 1 : 1 : 1 : test message 2
fred : 1 : 1 : 1 : test message 3
How do I go about uniquely identifying row 2?
如何唯一标识第 2 行?
in the Firebase Database they look like this:
在 Firebase 数据库中,它们如下所示:
-DatabaseName
-IuxeSuSiNy6xiahCXa0
approved: "1"
category: "1"
enabled: "1"
name: "Fred"
text: "test message 1"
-IuxeTjwWOhV0lyEP5hf
approved: "1"
category: "1"
enabled: "1"
name: "Fred"
text: "test message 2"
-IuxeUWgBMTH4Xk9QADM
approved: "1"
category: "1"
enabled: "1"
name: "Fred"
text: "test message 3"
采纳答案by Andrew Lee
To get the "name" of any snapshot (in this case, the ID created by push()) just call name() like this:
要获取任何快照的“名称”(在这种情况下,由 push() 创建的 ID)只需像这样调用 name() :
var name = snapshot.name();
If you want to get the name that has been auto-generated by push(), you can just call name() on the returned reference, like so:
如果你想获得由 push() 自动生成的名称,你可以在返回的引用上调用 name() ,如下所示:
var newRef = myDataRef.push(...);
var newID = newRef.name();
NOTE:snapshot.name()
has been deprecated. See other answers.
注意:snapshot.name()
已被弃用。查看其他答案。
回答by Dan Mindru
To anybody finding this question & using Firebase 3+
, the way you get auto generated object unique ids after push is by using the key
property (not method) on the promise snapshot:
对于发现此问题并使用的任何人Firebase 3+
,推送后获取自动生成的对象唯一 ID 的方法是使用承诺快照上的key
属性(而不是方法):
firebase
.ref('item')
.push({...})
.then((snap) => {
const key = snap.key
})
Read more about it in the Firebase docs.
在Firebase 文档中阅读更多相关信息。
As a side note, those that consider generating their own unique ID should think twice about it. It may have security and performance implications. If you're not sure about it, use Firebase's ID. It contains a timestamp and has some neat security features out of the box.
作为旁注,那些考虑生成自己的唯一 ID 的人应该三思而后行。它可能具有安全性和性能影响。如果您不确定,请使用 Firebase 的 ID。它包含一个时间戳,并具有一些开箱即用的简洁安全功能。
More about it here:
更多关于它的信息:
The unique key generated by push() are ordered by the current time, so the resulting list of items will be chronologically sorted. The keys are also designed to be unguessable (they contain 72 random bits of entropy).
push() 生成的唯一键按当前时间排序,因此生成的项目列表将按时间顺序排序。密钥也被设计为不可猜测的(它们包含 72 个随机位的熵)。
回答by Rima
snapshot.name()
has been deprecated. use key
instead. The key
property on any DataSnapshot (except for one which represents the root of a Firebase) will return the key name of the location that generated it. In your example:
snapshot.name()
已被弃用。使用key
来代替。key
任何 DataSnapshot 上的属性(代表 Firebase 根的除外)将返回生成它的位置的键名。在你的例子中:
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
var id = snapshot.key;
displayChatMessage(message.name, message.text, message.category, message.enabled, message.approved);
});
回答by Denis Markov
To get uniqueID
after push()
you must use this variant:
要获得成功uniqueID
,push()
您必须使用此变体:
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique key generated by push()
var postId = newPostRef.key;
You generate a new Ref
when you push()
and using .key
of this ref you can get uniqueID
.
Ref
当你push()
使用.key
这个 ref时你会生成一个新的,你可以获得uniqueID
.
回答by Brandon
As @Rima pointed out, key()
is the most straightforward way of getting the ID firebase assigned to your push()
.
正如@Rima 指出的那样,key()
是获取分配给您的push()
.
If, however, you wish to cut-out the middle-man, Firebase released a gist with their ID generation code. It's simply a function of the current time, which is how they guarantee uniqueness, even w/o communicating w/ the server.
但是,如果您希望去掉中间人,Firebase 发布了带有 ID 生成代码的要点。它只是当前时间的函数,这就是它们如何保证唯一性,即使没有与服务器通信。
With that, you can use generateId(obj)
and set(obj)
to replicate the functionality of push()
有了它,您可以使用generateId(obj)
并set(obj)
复制push()
/**
* Fancy ID generator that creates 20-character string identifiers with the following properties:
*
* 1. They're based on timestamp so that they sort *after* any existing ids.
* 2. They contain 72-bits of random data after the timestamp so that IDs won't collide with other clients' IDs.
* 3. They sort *lexicographically* (so the timestamp is converted to characters that will sort properly).
* 4. They're monotonically increasing. Even if you generate more than one in the same timestamp, the
* latter ones will sort after the former ones. We do this by using the previous random bits
* but "incrementing" them by 1 (only in the case of a timestamp collision).
*/
generatePushID = (function() {
// Modeled after base64 web-safe chars, but ordered by ASCII.
var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
// Timestamp of last push, used to prevent local collisions if you push twice in one ms.
var lastPushTime = 0;
// We generate 72-bits of randomness which get turned into 12 characters and appended to the
// timestamp to prevent collisions with other clients. We store the last characters we
// generated because in the event of a collision, we'll use those same characters except
// "incremented" by one.
var lastRandChars = [];
return function() {
var now = new Date().getTime();
var duplicateTime = (now === lastPushTime);
lastPushTime = now;
var timeStampChars = new Array(8);
for (var i = 7; i >= 0; i--) {
timeStampChars[i] = PUSH_CHARS.charAt(now % 64);
// NOTE: Can't use << here because javascript will convert to int and lose the upper bits.
now = Math.floor(now / 64);
}
if (now !== 0) throw new Error('We should have converted the entire timestamp.');
var id = timeStampChars.join('');
if (!duplicateTime) {
for (i = 0; i < 12; i++) {
lastRandChars[i] = Math.floor(Math.random() * 64);
}
} else {
// If the timestamp hasn't changed since last push, use the same random number, except incremented by 1.
for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {
lastRandChars[i] = 0;
}
lastRandChars[i]++;
}
for (i = 0; i < 12; i++) {
id += PUSH_CHARS.charAt(lastRandChars[i]);
}
if(id.length != 20) throw new Error('Length should be 20.');
return id;
};
})();
回答by Lew
You can update record adding the ObjectID using a promise returned by .then()
after the .push()
with snapshot.key
:
您可以使用with.then()
之后返回的承诺更新添加 ObjectID 的记录:.push()
snapshot.key
const ref = Firebase.database().ref(`/posts`);
ref.push({ title, categories, content, timestamp})
.then((snapshot) => {
ref.child(snapshot.key).update({"id": snapshot.key})
});
回答by Abdulmohsen Alabra
If you want to get the unique key generated by the firebase push()
method while or after writing to the database without the need to make another call, here's how you do it:
如果您想push()
在写入数据库时或写入数据库后获取 firebase方法生成的唯一密钥,而无需再次调用,请按以下步骤操作:
var reference = firebaseDatabase.ref('your/reference').push()
var uniqueKey = reference.key
reference.set("helllooooo")
.then(() => {
console.log(uniqueKey)
// this uniqueKey will be the same key that was just add/saved to your database
// can check your local console and your database, you will see the same key in both firebase and your local console
})
.catch(err =>
console.log(err)
});
The push()
method has a key
property which provides the key that was just generated which you can use before, after, or while you write to the database.
该push()
方法有一个key
属性,它提供刚刚生成的密钥,您可以在写入数据库之前、之后或写入数据库时使用该密钥。
回答by Deepesh
How i did it like:
我是如何做到的:
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference ref = mFirebaseDatabase.getReference().child("users").child(uid);
String key = ref.push().getKey(); // this will fetch unique key in advance
ref.child(key).setValue(classObject);
Now you can retain key for further use..
现在您可以保留密钥以供进一步使用..