如何将日期字符串数组转换为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
相关产品推荐
相关产品推荐

