生成类似于Firebase Firestore的唯一ID

4

我想在Firestore中创建一个带有唯一ID和名称的文档。为此,我想创建与Firebase Firestore唯一ID相同类型的唯一ID。

  • 如何创建带有自动生成的Firestore ID的唯一ID?
  • Firebase Admin SDK中是否有相关函数?

更新:

正如Frank van Puffelen在评论中提到的那样,AutoId是我正确的选择!

这是我在服务器端使用Node.js时使用的函数:

function generateUniqueFirestoreId(){
  // Alphanumeric characters
  const chars =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let autoId = '';
  for (let i = 0; i < 20; i++) {
    autoId += chars.charAt(Math.floor(Math.random() * chars.length));
  }

  return autoId;
}

4
请看AuthId.newId()。参见 https://dev59.com/AKjja4cB1Zd3GeqP8EOH#48284468 - Frank van Puffelen
就这样!请将此作为答案添加。 - Sean Stayns
一个更简短但等效的解决方案: const FirestoreAutoId = () => { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; return Array.from({ length: 20 }).reduce((acc) => \${acc}${chars.charAt(Math.floor(Math.random() * chars.length))}`); };` - Ale TheFe
1个回答

2

有一个uuid包可供使用。


我知道uuid包,但我需要一种类似于Firestore自动生成的ID。谢谢。 - Sean Stayns
你能具体说明一下“Firestore自动生成的ID”是什么意思吗? - Oliver
p8s3R6LZrE43MbJWyyKb - Jordan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接