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)
An easy way to grab random documents is get all the posts keys into an array ( docA , docB , docC , docD ) then shuffle the array and grab the first three entries, so then the shuffle might return something like docB , docD , docA .
If you have a very time-sensitive app, like online auctions where you can't have unpredictable delays (no one likes to lose because of something that we don't control), you shouldn't really use Firestore. You will have a hard time hiding the hiccups and you will only anger your users.
The best way to prevent duplicate nodes in firebase realtime database or duplicate documents in firebase firestore database is to keep a check in the app itself to verify that the record to be inserted doesn't already exist in the database by querying for data using key field in where clause.
If you leave the console open on a collection or document with busy write activity then the Firebase console will automatically read the changes that update the console's display. Most of the time this is the reason for unexpected high reads.
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)
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With