Search code examples
strapi

Retrieving model attributes in Strapi from model lifecycle methods


Inside my models directory (models belongs to /api/post), there are Post.js and Post.settings.json. I created an attribute title in Post.settings.json, and in Post.js I have:

beforeCreate: async (model, attrs, options) => {
  console.log(model.attributes.title);
};

I don't have any idea why it gives me an error error TypeError: Cannot read property 'title' of undefined. Does anyone know? Thanks in advance!


Solution

  • If you use mongoose, then this callback return only one parameter so if you would read tittle you should read reference from first parameter.

    beforeCreate: async (model) => {
      console.log(model.title);
    };
    

    https://strapi.io/documentation/3.0.0-beta.x/guides/models.html#lifecycle-callbacks