Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase cloud functions: is `createId()` available on the server side?

If I want to write to the database from my client side, I can inject an AngularFirestore instance and generate an id automatically using createId():

const individualId = this.angularFirestore.createId();

But if I want to do the same thing in a cloud function, using the Firestore admin API, I can't find an equivalent operation. I can create a Firestore instance in a cloud function by running

const db = admin.firestore();

However, the object that is created has no createId() function available.

Is there an equivalent to createId() that I can use within a cloud function?

like image 261
Rob Lyndon Avatar asked Mar 23 '26 13:03

Rob Lyndon


2 Answers

I understand from this issue and this article that "AngularFirestore.createId() generates a new id from a symbolic collection named '_'".

If you want to mimic this behaviour in a Cloud Function, you could use the doc() method of a CollectionReference without specifying any path. You will get a DocumentReference, and then you can use the id property to get the "last path element of the referenced document".

Something like the following:

const db = admin.firestore();
const docRef = db.collection('_').doc();
const newId = docRef.id;

Note that, as explained in the issue referred to above, it is a bit weird to "use a generic collection instead of an actual collection" to generate an id, because you would normally use the collection in which you want to create a new Document. But this is not a problem, according to this comment from James Daniels (who is a Firebaser), since the Firestore auto-generated ID is "just a random string and doesn't take the path into consideration at all".

like image 132
Renaud Tarnec Avatar answered Mar 25 '26 02:03

Renaud Tarnec


in JavaScript, for the new Firebase 9 (January 2022). In my case I am developing a comments section:

const commentsReference = await collection(database, 'yourCollection');
await addDoc(commentsReference, {
  ...comment,
  id: doc(commentsReference).id,
  date: firebase.firestore.Timestamp.fromDate(new Date())
});

Wrapping the collection reference (commentsReference) with the doc() provides an identifier (id)

like image 28
Ferran Buireu Avatar answered Mar 25 '26 03:03

Ferran Buireu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!