Could not convert MySQL data to Date
JordiGamez opened this issue · 1 comments
Hello!
I'm trying to obtain some articles from my MySQL database using Vapor-Fluent but there is something wrong with my Date type (I have read a little bit of Date type in Vapor but I'm not sure about how to solve this issue).
This is my Vapor-Fluent model:
final class ArticleModel: Model, Content {
static let schema = "tbl_article"
@ID(custom: .id)
var id: Int?
@Field(key: "title")
var title: String
@Field(key: "description")
var description: String
@Field(key: "checked_out_time")
var checkedOutTime: Date
init() { }
init(id: Int,
title: String,
description: String,
checkedOutTime: Date) {
self.id = id
self.title = title
self.description = description
self.checkedOutTime = checkedOutTime
}
}
This is my Controller:
func getContent(req: Request) async throws -> [ArticleModel] {
try await ArticleModel(on: req.db)
.sort(\.$checkedOutTime)
.all()
}
This is the format of my Date type in my tbl_article table (it's DATETIME type in my MySQL database):
2022-08-02 21:51:29
When I try to obtain the articles by visiting my URL, it returns the following error:
{"error":true,"reason":"invalid field: checked_out_time type: Date error: typeMismatch(Foundation.Date, Swift.DecodingError.Context(codingPath: [], debugDescription: \"Could not convert MySQL data to Date: 1970-01-01 00:00:00 +0000\", underlyingError: nil))"}
My question is:
What I have to change in order to make this work? I tried changing my model type to String but it didn't work, so maybe I have to change something related to the decoding process?
(I'm new to Vapor (I'm creating my first real MySQL connection and I don't know how to solve this issue regarding the Date type).).
Thanks!
After some tries, there was an issue in my DATETIME field where I was using 0000-00-00 00:00:00 instead of a valid value like 2022-08-02 21:51:29. After making that change (from zeros to valid date) it started working.