You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Mongoose返回纯日期对象,避免时区转换导致出生日期显示错误

根本原因

Mongoose 的 Date 类型默认查询返回的就是原生 JS Date 对象,你在前端拿到字符串是因为后端 Express 返回响应时,会自动对数据执行 JSON.stringify() 序列化,JS Date 对象在序列化时会被转为 ISO 8601 格式的字符串,JSON 协议本身不支持传输 Date 类型,所以不可能直接从后端传递 Date 对象到前端。

解决方案

方案1:Mongoose Schema 层预处理(推荐)

直接在字段定义中加 getter,序列化时直接返回格式化后的纯日期字符串,前后端都不需要额外处理:
修改你的 patientSchema 定义:

const patientSchema = new mongoose.Schema({
    firstName: String,
    middleName: String,
    lastName: String,
    addresses: [addressSubschema],
    // 改造dateOfBirth字段
    dateOfBirth: {
      type: Date,
      get: (value) => value ? value.toISOString().split('T')[0] : null
    },
    files: [{ type: mongoose.Schema.Types.ObjectId, ref: 'File' }],
    policies: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Policy' }],
    claims: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Claim' }],
    authorizations: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Authorization' }],
    statements: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Statement' }],
    documents: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Document' }],
    notes: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Note' }]
}, { 
  timestamps: true,
  // 开启getter生效配置,否则转JSON时getter不会执行
  toJSON: { getters: true },
  toObject: { getters: true }
})

配置后前端直接拿到 1990-05-05 格式的日期,直接渲染即可。

方案2:前端直接拆分ISO字符串

不想改后端的话,前端不需要转Date对象,直接切分ISO字符串拿到纯日期即可,完全避开时区问题:

// 渲染时直接处理
<p className="card-text">{props.data.dateOfBirth?.split('T')[0] || ''}</p>

方案3:前端转Date对象时按UTC读取

如果需要用Date对象做其他计算,读取时用UTC相关的方法,忽略本地时区偏移:

const formatBirthDate = (isoStr) => {
  if (!isoStr) return ''
  const dob = new Date(isoStr)
  return `${dob.getUTCFullYear()}-${String(dob.getUTCMonth() + 1).padStart(2, '0')}-${String(dob.getUTCDate()).padStart(2, '0')}`
}

// 渲染
<p className="card-text">{formatBirthDate(props.data.dateOfBirth)}</p>

内容的提问来源于stack exchange,提问作者Matthew Wolman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 20:27:04