Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Web Automatically insert createdAt and updatedAt fields

I've been using Firebase for one of my projects, but I've noticed that it doesn't automatically add the createdAt and updatedAt fields like Mongodb would add. How would I achieve the same functionality within Google Firebase? I've been looking for some sort of event or function I could override to add the fields but I haven't had any luck!

like image 996
Jordan Avatar asked Jul 28 '26 04:07

Jordan


1 Answers

You can achieve this using Firebase Cloud Functions. Please have a look at it.

Below is the sample code, which you can use it to achieve.

exports.generateCreatedOn = functions.database.ref('/messages/{pushId}/')
    .onWrite(event => {
      return event.data.ref.child('createdOn').set(new String(new Date()));
    });

Here, I've set the path to /messages/{pushId}/ this leads to repeated function triggers. So please find correct code below,

exports.generateCreatedOn = functions.database.ref('/messages/{pushId}/someKnownKey')
        .onWrite(event => {
          return event.data.ref.parent.child('createdOn').set((new Date()).getTime());
        });

but you have to apply same logic for whatever path you are using. And, I've set only createdOn, Please use similar logic for modifiedOn.

Hope this helps you.

like image 177
Nagaraj N Avatar answered Jul 30 '26 18:07

Nagaraj N



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!