Jerry Seigle
Jerry Seigle

Reputation: 457

In React or Javascript how do we provide a custom Document Id for Google Cloud Firestore

I am using React with cloud Firestore I am trying to add my own document id instead of one being automatic generated. If we can not do this, is there a way to get a callback to get the document id created when the data is submitted?

firebase.firestore()
.collection("user5d")
.document("custom-id")
.add({
    urn: randomNumber,
    line1: "some text",
    line2: "line 2 text",
    slashColor: "green",
    textColor: "white",
  });

Upvotes: 1

Views: 1077

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50920

To clarify the differences between the methods:

.add() -> Adds a document in the collection with an auto-generated document ID. You can use this on a CollectionReference only. For example:

firebase.firestore().collection("colName").add({...})

.set() -> Creates a new document in a collection however unlike .add(), you need to specify the document ID. This method can be called on a DocumentReference only. For example:

firebase.firestore().collection("colName").doc("docID").set({...})

.update() -> Updates an existing document in the collection. You need to specify the document ID. Similar to .set(), this method can be called on a DocumentReference only. For example:

firebase.firestore().collection("colName").doc("docID").update({...})

You can use .set() to update a document as well but it will overwrite rest of the fields unless you specify the merge property in SetOptions like .set({...}, {merge: true})

Upvotes: 6

Related Questions