TheLearner
TheLearner

Reputation: 2863

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?

Upvotes: 0

Views: 690

Answers (2)

Raquel Gutiérrez
Raquel Gutiérrez

Reputation: 31

    async afterUpdate(event){
      const rawBuilder = await strapi.db.connection.raw(
      "SELECT * FROM nameTable;"
      );

        console.log(rawBuilder, "RESULT:::");

    }

Example to execute a SQL query afer update some value in database or strapi, using knex strapi connection

Upvotes: 0

Jim LAURIE
Jim LAURIE

Reputation: 4120

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;
  }
},

Upvotes: 1

Related Questions