boriii
boriii

Reputation: 87

Firebase saving auto generated id to it's collection when creating collection

  const handleSubmit = async() => {
    const productsRef = firestore.collection("Products").doc();
    try {
      setIsLoading(true);
      var array = await uploadToS3();
      productsRef.set({
      caption: captionInput.value,
      user: auth.currentUser.uid,
      timeStamp:time
      })
    } catch (e) {
      console.log(e);
    } finally{
      setIsLoading(false);
    }
  };

Here is my code. When setting document to firebase, is there any ways that I can save my document's randomly generated id to the collection?

For example if my generated id is "hello world"

my collection has caption:'blah blah' timeStamp:'blah blah' user: 'uid' id: 'hello world'

Upvotes: 0

Views: 134

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599551

Since you pre-create the ref to the new document, you can get the id property from that reference:

productsRef.set({
  id: productsRef.id
  caption: captionInput.value,
  user: auth.currentUser.uid,
  timeStamp:time
})

Upvotes: 2

Related Questions