Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Firestore ID generator on the front end

I want to set my document ids on the front end, at the same time I set the doc, so I was wondering if there is a way to generate Firestore IDs, which could look like this:

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

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

I could use uuid or some other id generator package, but I'm looking for a Firestore id generator. This SO answer points to some newId method, but I can't find it in the JS SDK... (https://www.npmjs.com/package/firebase)

like image 224
samzmann Avatar asked Jun 13 '19 06:06

samzmann


Video Answer


1 Answers

EDIT: Chris Fischer's answer is more up to date, and using crypto to generate random bytes is probably more secure (although you might have trouble trying to use crypto in non node environments, like React Native for example).

Original Answer:

After asking in the RN Firebase discord chat, I was pointed to this util function deep in the react-native-firebase lib. It's essentially the same function as that the SO answer I mentioned in my question refers too (see the code in firebase-js-sdk here).

Depending on which wrapper you use around Firebase, the ID generation util is not necessarily exported/accessible. So I just copied it in my project as a util function:

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
}

Sorry, for the late reply :/ Hope this helps!

like image 140
samzmann Avatar answered Oct 18 '22 19:10

samzmann