在使用 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);
}