Maitreya Maitreya - 2 months ago 32
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

For this you can you the aggregation operator $dateToString

do something like:

db.table.aggregate(
   [
     {
       $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 : ret.name,
            date : ret.date
            >>all your model fields here<<
        };

        if (ret.date != undefined){
           only_year : ret.date.getFullYear();
        }

        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 ;-)

Comments