I am trying to add a map to a key in fire-store. Getting undefined in console and it is adding a empty map in firetsore.
I am uploading a multiple files at once in storage and getting imageUrls.
imageUrls={0:0.png,1:1.png} from this function.
const onUploadFiles = async (images) => {
let imageUrls = {};
Promise.all(
images.map(async (image) => {
const fileRef = storage.ref(`${scanID}/${chapterNumber}/${image.name}`);
await fileRef.put(image);
imageUrls[getFileName(image.name)] = await fileRef
.getDownloadURL()
.toString();
console.log(imageUrls[getFileName(image.name)]);
})
);
return imageUrls;
};
Once the files are uploaded I am trying to add this map to a document and adding it in firestore.
Utitlity function to store the name of the file as key.
const getFileName = (name) => name.replace(/\.[^/.]+$/, '');
Adding these url as a document.
//add chapter to firestore
const addChapter = async (images) => {
var chapter = {
id: uuidv4(),
title: title,
chapterNumber: chapterNumber,
};
await onUploadFiles(images)
.then((imageUrls) => {
chapter['images'] = imageUrls;
})
.catch((error) => {
console.log('Something went wring with database');
});
db.collection('chapters')
.doc(scanID)
.set(
{
[chapterNumber]: chapter,
},
//merge
{ merge: true }
)
.then(() => {
console.log('Done');
});
};
Expected output:
{
"0":{
"title":"title 1",
"id":"232131-321-312-331",
"chapterNumber":0,
"images":{
"0":"0.png",
"1":"1.png"
}
}
}
I am getting an empty map {} in firestore.
If I’m not misunderstanding, you would like to upload the images first to Firebase Cloud Storage buckets, and then retrieve the download URLs to include them in a document you are creating for a Firestore collection. If that’s the case, then in this related question there is a script that can help you upload images to Firebase Storage. I have tested this script, and it’s working on my test Node environment. Something I noticed from your code and the script I linked is that there is no firebaseStorageDownloadTokens property that provides a download token for your URLs:
const metadata = {
metadata: {
// This line is very important. It's to create a download token.
firebaseStorageDownloadTokens: uuid()
},
...
I have linked a guide related to downloading tokens and how to create them and obtain them. Finally, as to how to create Map objects from a variable to add to Firestore, the documentation provides an example of an object for Firestore:
const data = {
stringExample: 'Hello, World!',
booleanExample: true,
numberExample: 3.14159265,
dateExample: admin.firestore.Timestamp.fromDate(new Date('December 10, 1815')),
arrayExample: [5, true, 'hello'],
nullExample: null,
//Map object
objectExample: {
a: 5,
b: true
}
};