简体   繁体   中英

How can I insert new Firestore collection documents with unique GUID for an id?

I can generate them and insert them but that doesn't guarantee uniqueness.

Auto-generated Firestore ids look like this: 1234567890asdfghjklo (20-char utf-8 strings)

I want them to look like this in my collection: 2e8f782e-f162-41db-a3ab-e3e43cda2e28 (GUID)

Like I said I can create them and insert them along with each document but even though chances are slim there still is a chance an id will match a previous one.

So, one of 2 things:

1- I generate each document with a unique GUID I create separately. How can I ensure it's unique? (other than querying the collection to see if it already exists)

2- I toggle some hidden Firestore setting that makes it use GUID instead of 20-char UTF-8 in its auto-generated _ids

Can anyone help me with either of these?

Firestore ids are generated client-side. So I edited its code to generate a GUID and use it at insert time

function newId() {
// Alphanumeric characters
const chars =
  'ABCDEF0123456789';
let autoId = '';
for (let i = 0; i < 32; i++) {
  if(i === 8 || i === 12 || i === 16 || i === 20) autoId += "-";
  autoId += chars.charAt(Math.floor(Math.random() * chars.length));
}
return autoId;
}

EDIT: ended up using uuid npm just to make sure I end up with true randomness

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM