Jordan
Jordan

Reputation: 157

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!

Upvotes: 3

Views: 6249

Answers (1)

Nagaraj N
Nagaraj N

Reputation: 467

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.

Upvotes: 3

Related Questions