Monday, August 13, 2018

how to set custom value in updatedAt field in sails

Leave a Comment

I want to save updatedAt by 2 way.

1) If I'm passing some value in that object while saving data then it should save by that date else current date and time.

i.e Today current date is 2018-07-27 16:41:14 and if I set updatedAt = '2018-03-13 17:40:44' then it should be set as '2018-03-13 17:40:44'

2) It should save like autoUpdatedAt = True. So, if updatedAt is not set then it should take current date and time.

i.e Today current date is 2018-07-27 16:41:14 and if updatedAt is not set then it should be set as 2018-07-27 16:41:14


Thanks everyone for your effort. However, I found the solution as below.

Make below changes to specific model class.

  autoUpdatedAt: false,  updatedAt:{       type: 'datetime',       defaultsTo: function(){return new Date();},     } 

//LifeCycle callback

beforeUpdate: function (valueToBe, proceed) {     if (valueToBe.updatedAt == null) {       valueToBe.updatedAt = new Date();     }     return proceed();   }, 

2 Answers

Answers 1

You need to use a date-picker component and make it a required field that can easily default to the current date.

Answers 2

As mentioned by @mikermcneil, I would also suggest saving it as a JS timestamp. You can use momentJS to format it later when you need to. I would also handle the logic in the controller and not in the model. So for example, in the controller you could make a dataToUpdate object that may or may not contain the updatedAt data, then when you make your call to the DB it would look like:

Record.updateOne({id}).set({     someField: dataToUpdate.someField,     someOtherField: dataToUpdate.someOtherField,     updatedAt: dataToUpdate.updatedAt ? dataToUpdate.updatedAt : Date.now(),     ... }) 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment