首页 > 解决方案 > “您的过滤器包含一个字段‘状态’,它既没有出现在您的模型定义中,也没有出现在它的关系中”(Strapi)

问题描述

https://strapi.io/documentation/v3.x/guides/draft.html#apply-our-changes

我正在自定义我自己的 API,当然我想只过滤状态为已发布的帖子,所以我按照上面的文档来查看它是如何工作的。

我实际上使用了除了我自己的模型之外的确切代码,所以我的代码如下

'use strict';
const { sanitizeEntity } = require('strapi-utils');

/**
 * Read the documentation (https://strapi.io/documentation/v3.x/concepts/controllers.html#core-controllers)
 * to customize this controller
 */

module.exports = {
  async find(ctx) {
    let entities;

    console.log(ctx.query, 'before');
    ctx.query = {
      ...ctx.query,
      status: 'published',
    };

    console.log(ctx.query, 'after');
    if (ctx.query._q) {
      entities = await strapi.services.post.search(ctx.query);
    } else {
      entities = await strapi.services.post.find(ctx.query);
    }

    return entities.map(entity => sanitizeEntity(entity, { model: strapi.models.post }));
  }
};

然后我做一个正常的get API调用localhost:1337/posts

但我得到了这个错误

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "Your filters contain a field 'status' that doesn't appear on your model definition nor it's relations"
}

我稍后会根据需要为查询添加内容,但即使遵循文档,也会发生此错误,如果我没有覆盖默认控制器,API 工作正常。

提前感谢您的任何建议和建议。

编辑:

models/post.settings.json

{
   "kind":"collectionType",
   "collectionName":"posts",
   "info":{
      "name":"Post",
      "description":""
   },
   "options":{
      "increments":true,
      "timestamps":true,
      "draftAndPublish":true
   },
   "attributes":{
      "title":{
         "type":"string",
         "required":true
      },
      "images":{
         "collection":"file",
         "via":"related",
         "allowedTypes":[
            "images"
         ],
         "plugin":"upload",
         "required":false
      },
      "publishedAt":{
         "type":"datetime"
      },
      "expiresAt":{
         "type":"datetime"
      },
      "content":{
         "type":"richtext"
      },
      "link":{
         "type":"string"
      },
      "categories":{
         "collection":"category",
         "via":"posts"
      },
      "slug":{
         "type":"uid",
         "targetField":"title"
      },
      "originalPrice":{
         "type":"decimal"
      },
      "salePrice":{
         "type":"decimal"
      },
      "thumb":{
         "model":"file",
         "via":"related",
         "allowedTypes":[
            "images"
         ],
         "plugin":"upload",
         "required":false
      }
   }
}

标签: javascriptmongodbcontrollerstrapi

解决方案


正如错误消息所说,您的模型中没有status字段。如此处所述,将具有值、和的enumeration字段添加到您模型中。statusdraftpublishedarchived


推荐阅读