I want to add an Image (of a user generated post) in Firebase Storage, and its url in the Firestore DB. But there can be a lot of images, so i want to keep them in folders in Storage.
So the storage path looks like this:
/${uid}/posts/${postId}/${image1.name}
Here the postId
is the document reference Id of a new Post that i add in Firestore.
But since firestore does not support empty doc using the .add()
api, I have to a dummy write op, just to get the doc ref Id (which is postId)
db.collection('posts').add({isExist: true})
.then(docRef => { postDocRef = docRef; postId = docRef.id } )
Now i use this postId
in the storage path, and upload the image.
Once the upload is done, I receive its download url (getDownloadURL()
), which i want to store in the Firestore DB. So i had to trigger another write to the same doc and update it with the image download url.
postDocRef.update({ url : storageDownloadUrl })
This whole process causes two write ops to the Firestore.
Is there a better way that can result in single write to Firestore.
Few option that i thought:
- Generate postId locally on my own, that will act as document Id as well. [Does Firebase storage offer unique Id's for files?
- Do not use postId in the storage path, instead generate unique image.name
- Firestore considers providing reference to empty docs, like in realtime DB [Equivalent of .push in Firestore?