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

如何将日期字符串数组转换为Date类型并存储至数据库?

NestJS中MongoDB日期数组类型转换解决方案

问题背景

现有medicalData数组里的testDates是ISO日期字符串数组,但MongoDB Schema定义testDates为Date类型数组,需要把字符串转成Date对象后存入数据库,保证存储类型符合预期。

处理方案

1. 转换medicalData中的日期字符串

在medical.service.ts里遍历medicalData数组,将每一项的testDates字符串数组逐个转为Date对象:

// 处理日期字符串转Date对象
const processedMedicalData = medicalData.map(item => ({
  ...item,
  testDates: item.testDates.map(dateStr => new Date(dateStr))
}));

// 存入数据库
const result = await this.medicalRecordRepository.create({
  medicalData: processedMedicalData
});

2. 优化Schema类型定义

为让Mongoose更明确字段类型,修改medical.schema.ts中testDates的@Prop装饰器配置,显式指定类型为日期数组:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

class MedicalData {
  @Prop()
  name: string;

  @Prop()
  status: string;

  // 显式指定类型为Date数组
  @Prop({ type: [Date] })
  testDates: Date[];
}

@Schema()
export class MedicalRecord extends Document {
  @Prop({ type: [MedicalData] })
  medicalData: MedicalData[];
}

export const MedicalRecordSchema = SchemaFactory.createForClass(MedicalRecord);

说明

  • 必须手动转换日期字符串:Mongoose不会自动把字符串数组转为Date数组,需显式调用new Date()处理每个日期字符串;
  • Schema显式指定类型:能让Mongoose对字段类型做校验,避免存入不符合要求的数据类型。

内容的提问来源于stack exchange,提问作者Code The World

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:14:59