6

Im running a FIRESTORE database, and i want to create a random key with the same pattern as firestore does.

In the link i found the function that is called once i create a document with: 'db.ref.add()' to generate the key in client side:

https://github.com/firebase/firebase-js-sdk/blob/73a586c92afe3f39a844b2be86086fddb6877bb7/packages/firestore/src/util/misc.ts#L36

I need to do something like this:

let key = newId()
console.log(key)
db.ref().doc(key).set(data)
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
eeerrrttt
  • 549
  • 2
  • 7
  • 24

2 Answers2

11

it is very easy to use the firestore uid generator:

const uid = admin.firestore().collection("tmp").doc().id

this would do the trick without requiring to save some data

but in your specific example: if you don't specify any key it will be auto-generated by firestore:

await admin.firestore().collection("MY COLLECTION").doc().set(data)
giammin
  • 18,620
  • 8
  • 71
  • 89
1

Looks like you can just use the .add method instead of auto generating a uuid on your own.

https://firebase.google.com/docs/firestore/manage-data/add-data

// Add a new document with a generated id.
db.collection("cities").add({
    name: "Tokyo",
    country: "Japan"
})
.then(function(docRef) {
    console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
    console.error("Error adding document: ", error);
});
William Chou
  • 752
  • 5
  • 16