Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random Key firestore

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)
like image 352
eeerrrttt Avatar asked Apr 01 '18 05:04

eeerrrttt


People also ask

How do I get random documents from firestore?

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 .

When should you not use firestore?

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.

How do I prevent duplicates in firestore?

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.

Why are my firestore reads so high?

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.


2 Answers

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)
like image 65
giammin Avatar answered Sep 24 '22 02:09

giammin


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);
});
like image 26
William Chou Avatar answered Sep 22 '22 02:09

William Chou