【问题标题】:Model.create is not a function - strapiModel.create 不是一个函数-strapi
【发布时间】:2019-11-25 21:12:32
【问题描述】:

在 Strapi 的管理界面中创建模型时,我有一些独特的字段。

我意识到在api调用期间没有提供字段时,它会给出500的错误消息,而不是正确的错误消息。

我确实明白为什么会出现错误,因为我可以在后端控制台中看到日志,并且我已经浏览了诸如 https://github.com/strapi/strapi/issues/1189https://github.com/strapi/strapi/issues/1175 之类的帖子

阅读完这些问题后,我认为最好的方法是使用 /api/controllers 并创建一个诸如 create 之类的函数来覆盖提供的函数,但我收到 Model.create is not a function 的错误

我还没有在控制器中做太多事情,所以代码很精简。

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');
        }
    }
};

我已阅读问题单https://github.com/strapi/strapi/issues/1505 但我正在使用 带子:3.0.0-beta.17.5 节点:v10.17.0 npm:6.11.3 db:sqlite3(本地)postgresql(暂存)

有人知道我做错了什么吗?

提前感谢您的帮助和建议。

【问题讨论】:

    标签: javascript database sql-insert bookshelf.js strapi


    【解决方案1】:

    我建议你在这里查看默认的控制器功能https://strapi.io/documentation/3.0.0-beta.x/concepts/controllers.html#extending-a-model-controller

    您将看到如何使用服务函数来创建条目。

    我不建议你使用模型全局变量。

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

    【讨论】:

    • 我也读过,但猜我有错字或其他什么,因为它第一次不起作用。所以我最终做了const newArticle = new Article(ctx.request.body); newArticle.save() 你提供的东西就像一个魅力~ 不过我做newArticle.save() 可能有什么缺点?
    • P.S.所以通过create: async(ctx)实际上是覆盖和async create(ctx)是扩展?它们看起来太相似了,所以当我浏览文件时没有意识到
    • 它不会使用管理关系和其他东西的查询系统。关于定义create 函数,两者都是正确的并且会做同样的事情。您能否将问题设置为已回答,这将有助于了解此主题 ID OK ;) 谢谢。
    猜你喜欢
    • 2021-07-27
    • 2021-12-04
    • 1970-01-01
    • 2020-01-18
    • 2020-05-01
    • 2017-11-26
    • 1970-01-01
    • 2016-07-08
    • 2013-03-03
    相关资源
    最近更新 更多