Maitreya Maitreya - 1 year ago 159
Node.js Question

How to output mongoose/mongodb query with date fields that print strings with specific format?

I'm querying mongoDB via mongoose for some items that have fields of Date type.

I'm passing the result of this query to express as a web response.

Somewhere, this Date is being converted to a string. The output is "2016-09-28T03:19:51.066Z".

I want to choose the format of this string.

For the sake of a concrete example, let's say all I want is Date.getFullYear(). This should return "2016" instead of "2016-09-28T03:19:51.066Z".

Iterating over the query result is not a solution.

I tried using mongoose virtual methods with some schema options to no avail. I couldn't find anything that would intercept the stringification of this Date field.

Answer Source

For this you can you the aggregation operator $dateToString

do something like:

       $project: {
          fullYear: { $dateToString: { format: "%Y", date: "$date" } }

where $date is your date field.

If you just want it like year only in your frontend, you can also override the toJSON method and to a date.getFullYear() there.

include the below in your model:

YourSchema.set('toJSON', {
    transform: function (doc, ret, options) {
        var retJson = {
            _id : ret._id,
            name :,
            date :
            >>all your model fields here<<

        if ( != undefined){
           only_year :;

        return retJson;

You have to keep that when you add a field to your model you have to include it in the toJson, else it's not included ;-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download