I have a Date field in my Mongoose schema, which I'd like to transform into a conventional date for display. The obvious place to do this is in a getter, to avoid calling a prettifyDate
function all over the place. This doesn't work, as it seems mongoose is taking my post-getter string and giving it to the Date
constructor:
...
, date: {type: Date, get: function() { return 'foo'; }}
...
in my schema gives me:
Cast to date failed for value "foo"
when I fetch a document.
Is it possible to suppress this cast to Date
? Is there a better way that I'm missing?
The accepted answer is ok, but I think you should use a virtual for this. They were made especially for something like this.
schema.virtual('formatted_date').get(function () {
// Code for prettifying where you refer to this.date
return prettifiedDate;
});
This way you do not put an extra field in your schema (which is only used as a virtual)
In the current version of Mongoose (3.8) it works fine:
date: {type: Date, get: function(v) { return 'foo'; }} // yields 'foo' without errors
I've just been working on the exact same thing and have come up with this as a work around:
, date: {type: Date}
, formatted_date: {type : String, get : prettifyDate}
Then in the prettifyDate function reference: this.date
It's unlikely this is the best way to do it but it works. Remember to convert the date using .toISOString() to work with the raw ISO date in your function.