Search code examples
strapi

Unable to call lifecycle methods in Strapi models?


I have a Strapi project with a MongoDB database and a simple Post model. This model has, among others, a slug field with the following attributes:

type: string,
unique: true,
required: true

For testing purposes, I am attempting to modify this field's value before committing it to the DB, via one of Strapi's lifecycle methods:

module.exports = {
  // Before saving a value.
  // Fired before an `insert` or `update` query.
  beforeSave: async (model) => {
   // Set the password.
   const newslug = model.slug + '-test';
   model.slug = newslug;
  },
};

But the method just doesn't seem to get fired as expected when I save a post on my admin page. The post, along with its slug, gets upserted to the DB without the modification shown in the code above. Am I misunderstanding the functionality?


Solution

  • If you are using NoSQL database (Mongo)

    beforeSave: async (model) => {
      if (model.content) {
        model.wordCount = model.content.length;
      }
    },
    beforeUpdate: async (model) => {
      if (model.getUpdate().content) {
        model.update({
          wordCount:  model.getUpdate().content.length
        });
      }
    },
    

    If you are using SQL (SQLite, Postgres, MySQL)

    beforeSave: async (model, attrs, options) => {
      if (attrs.content) {
        attrs.wordCount = attrs.content.length;
      }
    },