I want to use a getter or setter for timestamps fields in the schema (mongoose schema) in order to change those dates formats when fetching them from the database.
let schema = new mongoose.Schema(
{
name: String,
dob: {
type: Date,
get: (date) => {
if (date) return date.toISOString().split("T") [0];
},
},
},
{
timestamps: true,
}
);
is there a clear solution for this ? Thanks in advance.
i found this solution works well.
let schema = new mongoose.Schema(
{
name: String,
dob: {
type: Date,
get: (date) => {
if (date) return date.toISOString().split("T") [0];
},
},
createdAt: {
type: Date,
get: (date) => timeSince(date),
}
updatedAt: {
type: Date,
get: (date) => timeSince(date),
},
},
{
timestamps: true,
toJSON: { getters: true, virtuals: true },
}
);
where timeSince is a function i defined.
and i use the json version of the model when i fetch it.