Search code examples
javascriptnode.jsstrapi

Cannot set date in beforeCreate hook - Strapi (beta14)


Created a news model: News.js

beforeCreate: async (model, attrs) => {
  if (attrs['Date'] === null) {
    model.set('Date', '2030-00-00 00:00:00+00');
  }
}

When i create the post, if user didn't fill date field i want it to be pre-filled automatically. But model.set() seems to have no effect when i create a new page.


Solution

  • I suggest you use beforeSave function.

    beforeSave: async (model, attrs, options) => {
      // detect if it's a creation or an update
      if (options.method === 'insert') {
        // statement for creation
        if (attrs['Date'] === null) {
          model.set('Date', '2030-00-00 00:00:00+00');
        }
      }
    }