2

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 Answer 1

5

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()

Sign up to request clarification or add additional context in comments.

5 Comments

Worked like a charm. Thank you for the help, Doug.
Great! On Stack Overflow, it's customary to upvote and accept helpful answers using the buttons on the left.
Hey Doug - I did upvote, but since I'm a noob, it doesn't reflect on the page, thought it does count behind the scenes.
You must know something about Stack Overflow that I don't! But could you try again anyway? It should show both a "1" and a green checkmark when you're done. They all end up like that. There aren't any hidden votes.
Checkmark is now green (I missed that). As for the upvote, the following message is displayed, "Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.