push - Firebase:如何为 key 生成唯一的数字ID?

标签 push firebase unique identity

我需要数字 ID 以便于人类阅读。如何在 Firebase 中获取它?

我想要按键的数字 ID,例如“000000001”、“000000002”、“00000003”、“00000004”。

我需要它的原因是因为这些ID将成为在线和离线的永久对象ID。我希望用户只需输入 URL“/objects/00000001”即可轻松浏览该对象页面。

我在这里问,因为我想知道这是否可以在不使用.priority、子属性等的情况下完成。我猜set方法可以做到这一点不知何故。如果不可能,请告诉我不,我可以接受这个答案。

最佳答案

我建议阅读 Firebase 文档。具体参见Saving Data Firebase JavaScript Web 指南的一部分。

来自指南:

Getting the Unique ID Generated by push()

Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it. The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated

// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push({
 author: "gracehop",
 title: "Announcing COBOL, a New Programming Language"
});

// Get the unique ID generated by push() by accessing its key
var postID = newPostRef.key;

来源:https://firebase.google.com/docs/database/admin/save-data#section-ways-to-save

  • 推送会生成一个新的数据路径,并以服务器时间戳作为其。这些键看起来像 -JiGh_31GA20JabpZBfa,所以不是数字。
  • 如果您想创建一个纯数字 ID,您可以将其作为对象的参数,以避免覆盖生成的键。
    • 键(新数据的路径)保证是唯一的,因此没有必要用数字键覆盖它们。
    • 您可以将数字 ID 设置为对象的子对象。
    • 然后,您可以使用 Firebase Queries 通过该 ID 子项查询对象.

来自指南:

In JavaScript, the pattern of calling push() and then immediately calling set() is so common that we let you combine them by just passing the data to be set directly to push() as follows. Both of the following write operations will result in the same data being saved to Firebase:

// These two methods are equivalent:
postsRef.push().set({
  author: "gracehop",
  title: "Announcing COBOL, a New Programming Language"
});
postsRef.push({
  author: "gracehop",
  title: "Announcing COBOL, a New Programming Language"
});

来源:https://firebase.google.com/docs/database/admin/save-data#getting-the-unique-key-generated-by-push

关于push - Firebase:如何为 key 生成唯一的数字ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28822054/

相关文章:

php - KO3 : Automatically generate unique alias/slug using ORM filters?

mysql - 当我们需要 100 万个唯一变体时,代码的最佳字符长度是多少?

php - iPhone SDK 推送通知随机失败

visual-studio-2010 - 如何将本地存储库推送到远程存储库?

ios - Auth.auth.currentUser.uid 即使登录有效也无法正常工作

java - 解包数据 firestore 查询返回的数组类型

ios - 将消息从 Azure 应用程序推送到 MonoTouch (iPhone) 应用程序,无需 Apple 推送通知

ios - APN BadDeviceToken iff 运行开发版本

angularjs 从 firebase 的链接播放音频

sql - 如何比较同一张表中的记录并查找缺失的记录