无法在Strapi模型中调用生命周期方法?

时间:2019-03-23 11:19:25

标签: strapi

我有一个带有MongoDB数据库和简单Post模型的Strapi项目。该模型除其他外,具有一个带有以下属性的slug字段:

type: string,
unique: true,
required: true

出于测试目的,我试图通过Strapi的生命周期方法之一将该字段的值提交到数据库之前进行修改:

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

但是,当我在管理页面上save发帖时,该方法似乎并没有按预期被解雇。该帖子及其slug将被升级到数据库,而无需进行上面代码中所示的修改。我误解了功能吗?

1 个答案:

答案 0 :(得分:1)

如果您使用的是NoSQL数据库(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
    });
  }
},

如果您使用的是SQL(SQLite,Postgres,MySQL)

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