Mongoose Date Schema

2019-08-16 07:45发布

问题:

I am using MongoDB, Mongoose, Express and Express Handlebars.

I have an <input type="date"> in my form, that posts to database, and my mongoose schema is defined like this:

var recordsSchema = new mongoose.Schema ({
   scheduled: Date,
});

The form inserts the time, but the output looks something like this:

Fri Oct 26 2018 00:00:00 GMT+0000 (UTC)

I want to format it so it appears as:

Fri Oct 26 2018

And not have anything else.

I tried using toString() method in the Handlebars template, but it doesn't work and server throws an error.

This is how it looks on the Express-Handlebars side:

{{ this.scheduled }} {{ this.scheduled.toString() }}

Can someone please let me know how to solve this?

Thanks.

回答1:

Try to add a custom getter in the schema to get the formatted date string as expected.

var recordsSchema = new Schema ({
  scheduled: Date,
  get: value => value.toDateString()
});