我想在前端设置文档is,同时set文档,所以我想知道是否有一种方法可以生成Firestore is,它可能如下所示:
const theID = firebase.firestore().generateID() // something like this
firebase.firestore().collection('posts').doc(theID).set({
id: theID,
...otherData
})我可以使用uuid或其他一些id生成器包,但我正在寻找一个修复id生成器。这就是答案指向一些newId法,但我在JS中找不到它.(https://www.npmjs.com/package/firebase)
发布于 2019-12-30 09:24:37
编辑:Chris的答案是最新的,使用crypto生成随机字节可能更安全(尽管在非节点环境中使用crypto可能会遇到困难,例如random )。
原始答案:
在react不和谐聊天中询问之后,我被指向了react本机- Firebase库中的这个功用函数。在本质上,它与我在问题中提到的SO答案所指的功能相同(参见firebase-js这里中的代码)。
根据您在Firebase周围使用的包装器,不一定导出/访问ID生成util。因此,我只是将其作为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
}很抱歉,迟来的回复:/希望这有帮助!
发布于 2020-05-29 19:07:19
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;
}摘自Firestore Node.js SDK:https://github.com/googleapis/nodejs-firestore/blob/4f4574afaa8cf817d06b5965492791c2eff01ed5/dev/src/util.ts#L52
发布于 2021-10-17 11:59:05
另一种选择是:
npm install @google-cloud/firestoreautoId:import {autoId} from "@google-cloud/firestore/build/src/util";https://stackoverflow.com/questions/56574593
复制相似问题