Tips on obtaining a dynamically generated document identifier before uploading a file to Firebase storage, and implementing it as a reference for web storage

Before sending a group of writes to Firestore with an automatically generated ID, I have a function that uploads an image file to Firebase storage. The code is set up to wait for the file to be uploaded before getting the download URL and then uploading the documents to Firestore.

However, I would like to use the Firestore document's auto-generated ID as the storage reference.

Below is the code snippet:

 try {
  // Replace "organization.uid" with the auto-generated ID by Firestore "organization_doc_ref.id".
  const storageRef = ref(this.storage, `organizations/${organization.uid}`);
  await uploadBytes(storageRef, blob).then(() => {
    console.info('Uploaded a blob or file!');
  });
  organization.logo_url = await getDownloadURL(storageRef);

  const batch = writeBatch(this.firestore);
  const organization_doc_ref = doc(
    collection(this.firestore, 'organizations')
  );
  batch.set(organization_doc_ref, organization);
  const usernameDocRef = doc(
    this.firestore,
    'usernames',
    organization.username
  );
  batch.set(usernameDocRef, { uid: organization_doc_ref.id });

  await batch.commit();
  console.log('Organization successfully created...');
} catch (error) {
  return console.error('Error writing document: ', error);
}

Answer №1

To ensure proper functionality, make sure to define the document reference before performing any other operations. The document's ID is locally generated and will only interact with the server upon calling batch.commit().

try {
  const organization_doc_ref = doc(
    collection(this.firestore, 'organizations')
  );

  const storageRef = ref(this.storage, `organizations/${organization_doc_ref.id}`);
  await uploadBytes(storageRef, blob);
  console.info('Successfully uploaded file!'); // use await instead of then() for consistency
  organization.logo_url = await getDownloadURL(storageRef);

  const batch = writeBatch(this.firestore);
  batch.set(organization_doc_ref, organization);
  const usernameDocRef = doc(
    this.firestore,
    'usernames', 
    organization.username
  );
  batch.set(usernameDocRef, { uid: organization_doc_ref.id }); // consider using imgId or orgId instead of uid

  await batch.commit();
  console.log('Organization created successfully...');
} catch (error) {
  return console.error('Error writing document: ', error);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Alternative Methods to Navigate Through Elements Using JQuery UI Autocomplete

After testing two different approaches: <div id = "team-search-container"> <label for="team-search" class = "text-center"> <input type = "text" id = "team-search"> </label> </div> With the following code sni ...

Display a list of items using ReactJS by mapping through an array of objects and rendering based on

How can I render a set of <div> </div> based on the items in an object without having to specify their names? In the code snippet below, I want the display of WorkObjectID and WorkObjectVal to be dynamic rather than static. If I include TempOb ...

Firebase Error: The creator key was not defined, which cannot be passed as undefined in JSON. Instead, use null

Currently, I'm working on a project using angularFire 0.8.2. The project is actually based on thinkster.io's angular-firebase tutorial. However, I've encountered a hurdle when trying to create a custom user profile and access the data within ...

What could be causing my jQuery code to not function properly?

I wrote a small piece of code in jQuery, but I am having trouble executing it. Can someone help me figure out what I'm doing wrong? <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"> & ...

The destroy method of Chart.js does not appear to have any impact on the

Hello, I've come across this issue in my react app that I need help with: this.chart = new Chart(node, options); // adding data to the chart ... this.chart.destroy(); this.chart = null; this.chart = new Chart(node, options); // adding data to the cha ...

Angular component with optional one-way binding for version 1.5 and above

Copied from the official AngularJS 1 documentation: To make a binding optional, simply add ?: <? or <?attr. What are the differences between the optional and non-optional one-way bindings? I can't seem to find the dissimilarities for the op ...

Organize table information using rowspan functionality

View of Current Table I am looking to implement a side column in my table using rowspan to group dates within each pay period. The goal is for a supervisor to be able to create a new pay period, which will assign a unique integer in the database and then ...

Is there a way to extract query parameters from the URL using getInitialProps?

There is a neat URL with query parameters that I am working with. http://localhost:3000/post/:id My goal is to extract the 'id' query parameter on the client side. static async getInitialProps({req, query: { id }}) { return { pos ...

Is there a way to validate form input before inserting it into a database using the onsubmit event?

Looking for a way to enhance the verification process of my signup form, I aim to ensure that all data entered is validated before being saved in the database. The validation process involves checking if the phone number consists only of numerical values a ...

Using JavaScript import may encounter issues when trying to access the same file or a different file

When importing something and using it, there are certain scenarios where it may not work as expected. For example: <html> <body> <button onclick="foo()">Click Me</button> </body> <script type="module"> ...

Is there a way to assign a specific color to individual users in a chat?

I have successfully implemented a chat feature using Pusher, but now I want to customize the appearance by changing the color of the username for the logged-in user when they are active in the conversation. Currently, both my username and another user&apos ...

Utilize string paths for images instead of requires when resolving img src and background-image URLs

I have successfully implemented image loading with webpack using the file loader, but only when I require or import images. I am curious about how create-react-app achieves the functionality where everything in the public folder is accessible, for example, ...

Guide to transferring parameters from one function to another in Javascript

For my automation project using Protractor and Cucumber, I have encountered a scenario where I need to use the output of Function A in Function B. While I was able to do this without Cucumber by extending the function with "then", I am facing difficulties ...

Using only native JavaScript Vanilla, Rails does not execute create.js via Ajax

Concerning Rails 4 and Vanilla JavaScript, I encountered an issue with my code for creating a Shop record via Ajax. The record is successfully created, but the create.js file is not being triggered as expected. A strange occurrence happens in Chrome where ...

Combining two observable entities

Utilizing Angular 4 and rxjs, the objective is to fetch data from two distinct servers in JSON format, merge this data, and exhibit it in a list by associating the list with an observable array. **Word Search Component TypeScript File:** @Component( ...

What is the process for implementing save-exact in bunfig.toml file?

Do bun repositories have a setting similar to .npmrc's save-exact configuration? I attempted to include save-exact = true in bunfig.toml but it did not have any effect. My bun version is 1.0.0. ...

How to show multiline error messages in Materials-UI TextField

Currently, I am attempting to insert an error message into a textfield (utilizing materials UI) and I would like the error text to appear on multiple lines. Within my render method, I have the following: <TextField floatingLabelText={'Input Fi ...

Looking for assistance with PHP if statement and troubleshooting iFrame issues

Using the PHP if statement below on my website: <?php if(empty($_GET['tid'])) echo '<iframe src="http://tracking.mydomain.com/aff_goal?a=33&goal_id=47" scrolling="no" frameborder="0" width="1" height="1"></iframe>'; ...

Execute an asynchronous function in Javascript, then output the returned data to the console

Is there a way to effectively handle the data returned from an async function? example: JS FILE: async function getData(){ try { $.getJSON('./data.json', (data) => { return data; }); } catch(error ...

Generating a Personalized XML Format Using Information from a Single MySQL Table Row by Row

If anyone can assist with this, I would greatly appreciate it: <warehouse> <frontbay> </frontbay> <bayrow> <bay> </bay> <bay> ...