以北京时间东八区为例:
const GuideTaskSchema = new Schema({
__v: { type: Number, select: false },
title: { type: String, required: true },
projectId: { type: Schema.Types.ObjectId },
path: { type: String, default: '' },
startTime: { type: Date, required: true },
endTime: { type: Date, required: true },
owner: { type: Schema.Types.ObjectId, ref: 'User', required: true },
})
GuideTaskSchema.path('startTime').get(v => {
// 自定义get方法,相当于可以自己format结果
// 查询的时候,将时间向后偏移8小时,格式化后输出
const t = moment(v).utcOffset(8).format('YYYY-MM-DD HH:mm:ss')
return t
}).set(v => {
// 自定义set方法,把处理好的值保存
// 保存数据库的时候,根据自己的需求,将时间写成ISO格式时间,并定义时区为+08:00
// ISO时间格式:
// 2020-01-01T00:00:00.000Z 以Z结尾为UTC时间,偏移时间为+HH:00或+HH:00
// 更多写法请参照百度百科 https://baike.baidu.com/item/ISO%208601/3910715?fr=aladdin
return new Date(`${v}T00:00:00.000+08:00`)
})
GuideTaskSchema.set('toObject', { getters: true }) // 这个也是必须的
将Schema如上配置后,在查询的时候需要调用文档(document)的toObject
方法,这样上面schema定义的set和get才会生效。
网友评论