简体   繁体   中英

ValidationError when posting JSON

I have this schema for authors:

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"
    }
  }
}

When I POST to http://localhost:9000/authors/ to create a new author I get this error:

error: Error of type InternalServerError found: ValidationError: books: Cast to Array failed for value "[ 'The Twits', 'The BFG' ]" at path "books"

This is the JSON I'm posting

{
    "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"
}

To the best of my knowledge this JSON is correct. The error seems to suggest there is an issue with the books array. Is this the case and if so, how do I fix it?

Adding Book schema:

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"
    }
  }
}

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

items: { type: "string" },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM