发布JSON时出现ValidationError

时间:2018-08-19 17:25:08

标签: javascript json node.js validationerror

我有这样的作者模式:

module.exports = {
  "id": "Author",
  "properties": {
    "name": {
      "type": "string",
      "description": "The full name of the author"
    },
    "description": {
      "type": "string",
      "description": "A small bio of the author"
    },
    "books": {
      "type": "array",
      "description": "The list of books published on at least one of the stores by this author",
      "items": {
        "$ref": "Book"
      }
    },
    "website": {
      "type": "string",
      "description": "The website url of the author"
    },
    "avatar": {
      "type": "string",
      "description": "The url of the avatar of this author"
    }
  }
}

当我发布到http://localhost:9000/authors/以创建新作者时,出现此错误:

  

错误:发现类型为InternalServerError的错误:ValidationError:书籍:路径“ books”上的值“ ['The Twits','The BFG']”的转换为数组失败

这是我要发布的JSON

{
    "name": "Roald Dahl",
    "description": "Writes childrens novels",
    "books": [
        "The Twits",
        "The BFG"
    ],
    "website": "www.roalddahl.com",
    "avatar": "https://www.natgeokids.com/wp-content/uploads/2016/11/Roald-Dahl-1-1.jpg"
}

据我所知,此JSON是正确的。该错误似乎表明books数组存在问题。是这种情况,如果是,该如何解决?

添加Book模式:

module.exports = {
  "id": "Book",
  "properties": {
    "title": {
      "type": "string",
      "descrtiption": "The title of the book"
    },
    "authors": {
      "type": "array",
      "description": "List of authors of the book",
      "items": {
        "$ref": "Author"
      }
    },
    "isbn_code": {
      "type": "string",
      "description": "The stores where clients can buy this book"
    },
    "stores": {
      "type": "array",
      "description": "The stores where clients can buy this book",
      "items": {
        "type": "object",
        "properties": {
          "store": {
            "$ref": "Store"
          },
          "copies": {
            "type": "integer"
          }
        }
      }
    },
    "genre": {
      "type": "string",
      "description": "Genre of the book",
    },
    "description": {
      "type": "string",
      "description": "Description of the book"
    },
    "reviews": {
      "type": "array",
      "items": {
        "$ref": "ClientReview"
      }
    },
    "price": {
      "type": "number",
      "minimum": 0,
      "description": "The price of this book"
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您将使用books字段作为字符串数组发布JSON,因此您的验证器对象应指定:

items: { type: "string" },