在前端访问 Firestore ID 生成器

sam*_*ann 6 javascript firebase google-cloud-firestore

我想在前端设置我的文档 ID,同时设置我set的文档,所以我想知道是否有一种方法可以生成 Firestore ID,它可能如下所示:

const theID = firebase.firestore().generateID() // something like this

firebase.firestore().collection('posts').doc(theID).set({
    id: theID,
    ...otherData
})

Run Code Online (Sandbox Code Playgroud)

我可以使用uuid或其他一些 id 生成器包,但我正在寻找 Firestore id 生成器。这个 SO 答案指向一些newId 方法,但我在 JS SDK 中找不到它......(https://www.npmjs.com/package/firebase

sam*_*ann 10

编辑:Chris Fischer 的答案是最新的,并且crypto用于生成随机字节可能更安全(尽管您可能无法尝试crypto在非节点环境中使用,例如 React Native)。

原答案:

在 RN Firebase 不和谐聊天中询问后,有人指出我在 react-native-firebase 库深处的这个 util 函数。它本质上与我在问题中提到的 SO 答案所指的功能相同(请参阅此处的firebase-js-sdk 中的代码)。

根据您在 Firebase 周围使用的包装器,ID 生成实用程序不一定导出/可访问。所以我只是将它复制到我的项目中作为一个 util 函数:

export const firestoreAutoId = (): string => {
  const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

  let autoId = ''

  for (let i = 0; i < 20; i++) {
    autoId += CHARS.charAt(
      Math.floor(Math.random() * CHARS.length)
    )
  }
  return autoId
}
Run Code Online (Sandbox Code Playgroud)

抱歉,回复晚了:/希望这会有所帮助!


小智 5

import {randomBytes} from 'crypto';

export function autoId(): string {
  const chars =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let autoId = '';
  while (autoId.length < 20) {
    const bytes = randomBytes(40);
    bytes.forEach(b => {
      // Length of `chars` is 62. We only take bytes between 0 and 62*4-1
      // (both inclusive). The value is then evenly mapped to indices of `char`
      // via a modulo operation.
      const maxValue = 62 * 4 - 1;
      if (autoId.length < 20 && b <= maxValue) {
        autoId += chars.charAt(b % 62);
      }
    });
  }
  return autoId;
}
Run Code Online (Sandbox Code Playgroud)

取自Firestore Node.js SDK: https://github.com/googleapis/nodejs-firestore/blob/4f4574afaa8cf817d06b5965492791c2eff01ed5/dev/src/util.ts#L52


小智 5

另一种选择是:

  1. 安装@google-cloud/firestore npm install @google-cloud/firestore

  2. 然后autoId在需要的时候导入使用:

import {autoId} from "@google-cloud/firestore/build/src/util";
Run Code Online (Sandbox Code Playgroud)