0
votes

Regarding Firestore, Cloud Function, Typescript.

My goal:

  1. New User registers with app.
  2. New User triggers cloud function (typescript) to populate my Firestore UserAccounts collection with a new doc.
  3. Cloud Function uses the User UID from Firebase Auth as the Document ID for the new document being added to the UserAccounts collection.

Problem: A new doc is created, however, it uses the auto-gen Doc ID and the doc itself has an additional Doc ID field within.

Note: Using the Firebase Website, I can manually add new documents to a collection using my own Doc ID.

Example Code :

export const onNewRegistration = functions.auth.user().onCreate((user) => {
    functions.logger.info("New User Created - Name: ", user.email, ", UID: ", user.uid);
    const db = admin.firestore();
    const newdoc = db.collection('UserAccounts').add({
        'Document ID': user.uid,
        State: 'Unverified'
    });

    return newdoc;
});

Thank you, all.

1

1 Answers

2
votes

If you know the ID of the document to create, don't use add(). add() always creates a new document with a new random ID.

You should instead use doc() to create a new document reference with the given ID, then use set() to write it:

return db.collection('UserAccounts').doc(user.uid).set({
    // fields and values here will be written to the document
});

See also: Firestore: difference between set() and add()