繁体   English   中英

如何在上传文件到Firebase存储之前获取自动生成的文档ID,并将该ID用作Web的存储参考?

[英]How to get auto-generated document ID before uploading file to Firebase storage, and use that ID as a storage reference for Web?

在使用 Firestore 自动生成的 ID 将一批写入提交到 Firestore 之前,我有一种方法可以将图像文件上传到 Firebase 存储。 在将文件上传到Firestore之前,开发代码等待文件上传获取下载URL。

但是,我想使用 Firestore 文档的自动生成的 ID 作为存储参考。

这是我的代码:

 try {
  // To 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);
}

您只需要重新排序您的说明,以便首先定义文档参考。 文档的 ID 将在本地生成,并且在您调用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('Uploaded a blob or file!'); // avoid putting this in then() if using await
  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 }); // avoid using uid as it is often linked with the current Firebase Auth user's ID, use imgId, orgId or something similar

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2023 STACKOOM.COM