MongoDB validation schema:
bsonType: "object",
required: ["createdAt"],
properties: {
createdAt: {
bsonType: "date"
}
}
Java class:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@MongoEntity(collection = "dogs")
public class Dog {
private OffsetDateTime createdAt;
}
Java object creation:
var dog = new Dog();
dog.setCreatedAt(OffsetDateTime.now());
Insert document:
mongoDatabase.getCollection("dogs", Dog.class).insertOne(dog);
Retrieve document:
var dog = col.find().into(new ArrayList<>()).get(0);
System.out.println(dog.getCreatedAt()); //1970-01-20T21:13:08.290+01:00
System.out.println(OffsetDateTime.now()); //2024-04-29T12:58:10.168902949+02:00
In database the 1970 date is set.
Does MongoDB support OffsetDateTime? Is something missing to insert the date in correct format?
The MongoDB Java driver didn't support OffsetDate and OffsetDateTime.
You need to create a Codec and a CodecProvider to support them, Quarkus will automatically detect them add the to the client: https://quarkus.io/guides/mongodb#simplifying-mongodb-client-usage-using-bson-codec