Home > Enterprise >  How can I get Firebase Storage downloadable array of links and set it to object for storing in mongo
How can I get Firebase Storage downloadable array of links and set it to object for storing in mongo

Time:12-30

My question is how do I set array of image links to my createAd function for storing the result into MongoDB database. Console log gives the getLinks result array as below. However, always I'm getting empty [] array for photos[] field in MongoDB database collection.

enter image description here

getlink function do the upload image to firestore and get downloadable url

const getLinks = (values) => {
    const array = [];
    values.adImgs.map((image: any) => {
        const imgPath = `ad_images/${image.name   v4() }`;
        const imageRef = ref(storage, imgPath);
        uploadBytes(imageRef, image).then((snapshot) => {
            getDownloadURL(snapshot.ref)
                        .then((url)=> array.push(url));
        })
    });
    return array;
}

This is the function to store data into MongoDb database

const createAdd = async (values) => {
   const newObj: any = {
      title: values.title,
      photos: getLinks(values)
   }
  await createPost(newObj);
}

CodePudding user response:

The uploadBytes() and getDownloadURL() functions both return a promise. You are returning an empty before waiting for the files to upload. Try refactoring the code as shown below:

// async function 
const getLinks = async (values) => {
  const uploadPromises = values.adImgs.map((image) => {
    const imgPath = `ad_images/${image.name   v4() }`;
    const imageRef = ref(storage, imgPath);
    return uploadBytes(imageRef, image);
  })

  // Upload all images
  const res = await Promise.all(uploadPromises);

  const links = await Promise.all(res.map((r) => getDownloadURL(r.ref)));
  return links;
}


const createAdd = async (values) => {
   const newObj: any = {
      title: values.title,
      photos: await getLinks(values) // <-- add await
   }
  await createPost(newObj);
}
  • Related