javascriptdatabasesql-insertbookshelf.jsstrapi

Model.create is not a function - strapi


I have a few unique fields when creating model in strapi's admin ui.

I realized that when field is not provided during the api call, it'll give an error message of 500 instead of the proper error message.

I do understand why there's an error since I can see the log in backend console and I have scanned through posts such as https://github.com/strapi/strapi/issues/1189 and https://github.com/strapi/strapi/issues/1175

After reading those issues, I believe the best way is to go /api/controllers and create a function such as create to override the one provided but I get an error of Model.create is not a function

I have not do much in the controller yet so code is slim.

module.exports = {
    /* Strapi has default create function
     * But because of the error message it provide is vague, will have to customize the controller */
    create: async (ctx) => {
        try {
            console.log(ctx.request.body, 'ctx');
            const article = await Article.create(ctx.request.body);
            console.log(article, 'article');
        } catch (e) {
            console.log(e, 'error');
        }
    }
};

I have read the issue ticket https://github.com/strapi/strapi/issues/1505 But I am using strapi: 3.0.0-beta.17.5 node: v10.17.0 npm: 6.11.3 db: sqlite3 (local) postgresql (staging)

Anyone know what I might have done wrong?

Thanks in advance for any help and advise.


Solution

  • I suggest you check the default controller functions here https://strapi.io/documentation/3.0.0-beta.x/concepts/controllers.html#extending-a-model-controller

    You will see how to use service functions to create entries.

    I don't suggest you to use Model Global variables.

    const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
    
    module.exports = {
      /**
       * Create a record.
       *
       * @return {Object}
       */
    
      async create(ctx) {
        let entity;
        if (ctx.is('multipart')) {
          const { data, files } = parseMultipartData(ctx);
          entity = await strapi.services.restaurant.create(data, { files });
        } else {
          entity = await strapi.services.restaurant.create(ctx.request.body);
        }
        return sanitizeEntity(entity, { model: strapi.models.restaurant });
      },
    };