0
votes

When uploading an image in Storage, I want to be able to get the fullPath or an imageURL and save it under my 'Articles' documents in Cloud Firestore. So basically, I have a form with a 'title' and the upload image should be a part of it. However, I don't know how to make each image know to which article it belongs to. This is what I have so far but I'm not sure it's fine. I only manage to save the images in Storage, nothing else.

What do I do so that the image knows to which article it belongs to?

function UploadFile(props) {
  const { documentId } = props;
  const [fileUrl, setFileUrl] = React.useState(null);

  const onFileChange = async (e) => {
    const file = e.target.files[0];
    const storageRef = firebase.storage().ref();
    const fileRef = storageRef.child(file.name);
    await fileRef.put(file);
    if (documentId) {
      setFileUrl(
        await fileRef.getDownloadURL().then((fileUrl) => {
          firebase
            .firestore()
            .collection("articles")
            .doc(documentId)
            .update({
              fileUrl: fileUrl,
            })
            .then(() => {
              setFileUrl("");
            });
        })
      );
    }
  };

Firestore doc

1

1 Answers

3
votes

There are two primary strategies for associating an object in Cloud Storage to some other record in a database.

  1. Use object metadata to store a locator to the database record. Object metadata is essentially a set of key/value pairs of strings attached to the object. You could store the path to the related Firestore document in metadata, and use that to find the document easily.

  2. Name the object in storage the same as it's named in Firestore. Firestore documents often have random IDs. You can use the same random ID in the name of the object path. All you have to do is parse the path of that object to find the document ID, and use that to build the path to the related document. The way you create the path to the document in Firestore and the path to the object in Storage don't have to be exactly the same, but it should be clear how to convert one to the other.