How can I format a date coming from MongoDB?

前端 未结 7 643
青春惊慌失措
青春惊慌失措 2021-01-30 05:19

I\'m using Jade to render my views from within Express.js. I am saving documents in MongoDB and using Mongoose to access my documents. I am saving a default date created when a

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-30 05:54

    Actually, you don't need another attribute in your Mongoose schema to store the creation date, as the _id has that information. Instead, you can create a virtual on your Mongoose schema, like this:

    YourSchema.virtual('date')
      .get(function() {
        return this._id.generationTime;
      });
    

    That would return the raw Javascript date as the .date attribute for each document.

    Then you can take that one step further and format the date you way you want to in that virtual:

    YourSchema.virtual('date')
      .get(function() {
        return this._id.generationTime.toDateString();
      });
    

提交回复
热议问题