mongodb 如何将日期字符串数组转换为日期?

mwg9r5ms  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(110)

需要将日期类型的数组从字符串转换为日期。
下面是输入:

  1. medicalData = [
  2. {
  3. name: 'Allergy',
  4. status: 'Normal',
  5. testDates: ['2023-07-02T13:21:29.643Z', '2023-07-03T13:21:29.644Z']
  6. },
  7. {
  8. name: 'Asthma',
  9. status: 'Deficient',
  10. testDates: ['2023-08-02T13:21:29.643Z', '2023-08-03T13:21:29.644Z']
  11. }
  12. ];

字符串
medical.service.ts:

  1. const result = await this.medicalRecordRepository.create({
  2. medicalData: medicalData // need to know how to use new Date() here
  3. });


medical.schema.ts:

  1. class MedicalData {
  2. @Prop()
  3. name: string;
  4. @Prop()
  5. status: string;
  6. @Prop()
  7. testDates: [Date];
  8. }
  9. export class MedicalRecord extends Document {
  10. @Prop()
  11. medicalData: MedicalData[];
  12. }


我需要的testDates被保存在数据库中的日期不是日期字符串数组数组。
需要一些有价值的帮助

9avjhtql

9avjhtql1#

一种可行的方法是将医疗数据map两次

  • 每个医疗数据条目的外部map,它使用参数的解构和rest属性,以及spread syntax,用于创建该数据条目的副本
  • 和一个嵌套的map,它创建每个数据条目的testDates数组的另一个变体,其中后者的项目是Date示例...
  1. const medicalData = [{
  2. name: 'Allergy',
  3. status: 'Normal',
  4. testDates: ['2023-07-02T13:21:29.643Z', '2023-07-03T13:21:29.644Z'],
  5. }, {
  6. name: 'Asthma',
  7. status: 'Deficient',
  8. testDates: ['2023-08-02T13:21:29.643Z', '2023-08-03T13:21:29.644Z'],
  9. }];
  10. /*
  11. const result = await this.medicalRecordRepository.create({
  12. medicalData: medicalData.map(({ testDates, ...rest }) => ({
  13. ...rest,
  14. testDates: testDates.map(dateStr => new Date(dateStr))
  15. }))
  16. });*/
  17. console.log({
  18. medicalData: medicalData.map(({ testDates, ...rest }) => ({
  19. ...rest,
  20. testDates: testDates.map(dateStr => new Date(dateStr))
  21. }))
  22. });

字符串

备注:

上面stack-snippet的SO特定日志记录将每个Date示例呈现为其自身的字符串化版本。浏览器的控制台日志记录将显示一个带有日期示例的数据结构。

展开查看全部

相关问题