Search code examples
javascriptpostgresqlnestjsdtonestjs-typeorm

Nestjs + postgresql +dto store jsonb gives must be a json string error


Currently having nestjs setup up with postgresql as database. I know that postgresql columns can store json, so I am trying to play around with it but I keep on getting the error

{
    "message": [
        "content must be a json string"
    ],
    "error": "Bad Request",
    "statusCode": 400
}

I wonder what's wrong with my setup.

My entities includes this column

  @Column('jsonb', { nullable: false, default: {} })
  content: IContent;

In my CreateUpdateDTO, I have the following.

  @IsJSON()
  content: IContent;

IContent is just an interface

export interface IContent {
  messages: string [];
  detail: string;
}

Then in postman I have this as raw json body

{
  "content": {
     "messages": ["testing", "testing", "123"],
     "detail": "some detail"
  }
}

Then I'd get that error of "content must be a json string"

Wonder where I setup wrong or missed something?

Thank you so much in advance for any suggestions and advices.


Solution

  • According to docs:

    @IsJSON() Checks if the string is valid JSON.

    However

    {
      "messages": ["testing", "testing", "123"],
      "detail": "some detail"
    }
    

    Is obviously not a string so the validation failure is expected. See JSON Object Literals
    Here you can find an example of how to use @IsJSON()

    But think in your use case you don't need the decorator, your JSON payload should be accepted without any issues, and the content property will be automatically converted to JSON and stored in the jsonb column.