I want to store the user information in the document with its id(not the document id). I want to generate the id particular formate like XYZ0001, where the last 4 digits will automatically increase whenever a new user adds on. Eg, XYZ0001, XYZ0002 like that. I have tried this...
return firestore
.collection("xyzData")
.doc(resp.user.uid)
.set({
firstName: newUser.firstName,
lastName: newUser.lastName,
email: newUser.email,
ca_id: "XYZ" + pad(firestore.collection("xyzData").count())
})
.then
where pad() is a function which gives me last 4 digits
function pad(n) {
var s = "000" + n;
return s.substr(s.length - 4);
}
but this is giving me an error that count() is not a function
Also, I was thinking of one another way where I can read the value of the last id and then increase it by one for the next user, bust won't be able to implement it.
At the Firebase Summit 2022, Firebase announced that now Cloud Firestore supports the count() aggregation query. count() allows you to determine the number of documents in a collection or query.
Note that there is no count() method for a CollectionReference. If you want to know the number of documents in a collection you need to call the asynchronous get() method to get a QuerySnapshot and then use the size property. However, you can not pass a call to get() as a property of an object.
The solution is to maintain you own counter.
There are two standard ways for that:
firebase.firestore.FieldValue.increment()As explained in the doc you can call firebase.firestore.FieldValue.increment() to increment a specific field of a Firestore document. For example, you could have one document in a counter Collection that you increment and read each time you want to get a new value from the sequence. Depending on your exact use case, you may need to use a Transaction.
Also note that "you can update a single document only once per second".
If you need to update your counter document more than once per second, you should use a Distributed counter as explained in the doc.
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