Vapor 4 and Fluent: How to add a (Postgres)-JSONB column

Hi there,

I want to store a JSON string in a Postgresql-JSONB column. Googling that topic I was only able to find this:

https://losingfight.com/blog/2018/11/25/how-to-add-a-postgresql-jsonb-column-in-vapors-fluent/

but it is about Vapor 3.

My question is: would I still do it the way it is described in above link or do things have changed for Vapor 4?

Kind regards,

Lars

I believe you want something like this:

import Foundation
import Fluent

final class MyModel: Model {
    static let schema = "schema"
    @ID public var id: UUID?
    @Field(key: "json") public var json: Nested
    @Field(key: "jsonb") public var jsonb: Data
    
    struct Nested: Codable {
        let thing: Int
    }
}

struct MyModelMigration: Migration {
    func prepare(on database: Database) -> EventLoopFuture<Void> {
        database.schema("schema")
            .field(.id, .uuid, .identifier(auto: false))
            .field(.string("json"), .json, .required)
            .field(.string("jsonb"), .custom("JSONB"), .required)
            .create()
    }
    
    func revert(on database: Database) -> EventLoopFuture<Void> {
        database.schema("schema").delete()
    }
}
Terms of Service

Privacy Policy

Cookie Policy