Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File metadata is not getting updated in Firestore Storage

I have created a Cloud Function that trigger on any new file upload in Firebase Storage. Once successful upload function will update its metadata, but even though setting new metadata with 'setMetadata()' is not getting applied. There is no error during the process and but on checking for updated metadata, the new one is not reflecting.

exports.onImageUpload = functions.storage.object().onFinalize(async (object) => {  
  const storageRef = admin.storage().bucket(object.bucket);

  var metadata = {
      'uploader': 'unknown'   
  }

  await storageRef.file(object.name).setMetadata(metadata).then(function(data) {
    console.log('Success');
    console.log(data);
    return;
  }).catch(function(error) {
    console.log(error);
    return ;
  });
  return;
}); 

There is no error, and on Cloud Function log its printing 'Success' message. Also "metageneration: '2'" property also got updated, which means it should have updated metadata with new values, but it didn't.

like image 761
Raj Singh Avatar asked Sep 30 '19 16:09

Raj Singh


People also ask

What is metadata in Firebase storage?

File metadata contains common properties such as name , size , and contentType (often referred to as MIME type) in addition to some less common ones like contentDisposition and timeCreated . This metadata can be retrieved from a Cloud Storage reference using the getMetadata() method.

What is file metadata?

What is file metadata? Metadata provides information about something, usually in greater or more organized detail. File metadata is when this metadata is about a digital file type or is stored in a dedicated file for future use.

How do I rename files in Firebase storage?

There are no move or rename operations provided by the Firebase SDKs. You would have to write code to download the file, upload it again with the new name, then delete the original. It's better if you don't rely on the name of files in storage.


1 Answers

The problem comes from the fact that if you want to set custom key/value pairs they must be in the metadata key of the object you pass to the setMetadata() method, i.e. the metadata object in your case. This is explained in the API Reference Documentation for node.js.

So the following will work:

exports.onImageUpload = functions.storage.object().onFinalize(async (object) => {
    const storageRef = admin.storage().bucket(object.bucket);

    var metadata = {
        metadata: {
            'uploader': 'unknown'
        }
    }

    try {
        const setFileMetadataResponse = await storageRef.file(object.name).setMetadata(metadata);
        console.log('Success');
        console.log(setFileMetadataResponse[0]);
        return null;
    } catch (error) {
        console.log(error);
        return null;
    }
});
like image 83
Renaud Tarnec Avatar answered Oct 06 '22 00:10

Renaud Tarnec