将 CSV 导入 MongoDB 时,路径中的值“无效日期”导致 Cast to date 失败

问题描述

我正在使用 csvtojson npm 包将 csv 数据导入到 mongodb,但我收到了 ValidationError: Contact validation Failed: contactdateofbirth: Cast to date Failed for value "Invalid Date" at path "contactdateofbirth",dayoftheyear: Cast to Number路径“dayoftheyear”错误中的值“NaN”失败。

这是我目前所做的:

[
  {
    contactsalutation: 'Mr',contactname: 'Jone White',contactaddress: '456 Some Road',contactnumber1: '12345678',contactnumber2: '87654321',contactemail: 'demo@demo.com',contactdateofbirth: '23/01/1970',contactremark: 'he is a very patient customer'
  },{
    contactsalutation: 'Ms',contactname: 'Jane doly',contactaddress: '123 Some Other Road',contactnumber1: '81234567',contactnumber2: '81234578',contactemail: 'demo@hotmail.com',contactdateofbirth: '28/02/1970',contactremark: 'she is also a very patient customer'
  }
]


  csvtojson()
      .fromFile(csvFilePath)
      .then(jsonObj => {
        console.log(jsonObj);
        jsonObj.forEach(items => {
          const importContact = new Contact({
            contactsalutation: items.contactsalutation,contactname: items.contactname,contactaddress: items.contactaddress,contactnumber1: items.contactnumber1,contactnumber2: items.contactnumber2,contactemail: items.contactemail,contactdateofbirth:new Date(items.contactdateofbirth),dayoftheyear: (moment(new Date(items.contactdateofbirth)).format('YYYY/MM/DD') == '1900/01/01') ? '0' : moment(new Date(items.contactdateofbirth)).dayOfYear(),contactremark: items.contactremark,});
          importContact.save()
        })
      })

这是架构的简短版本:

    contactdateofbirth:{
        type: Date,default: '1900-01-01'
    },dayoftheyear:{
        type:Number,default: '0'},

我尝试使用新日期但未能转换为正确的日期。我在这里缺少什么?非常感谢,并非常感谢任何帮助。再次感谢。

解决方法

我知道我错过了什么>这是 CSV 中的日期格式

[
  {
    contactsalutation: 'Mr',contactname: 'Jone White',contactaddress: '456 Some Road',contactnumber1: '12345678',contactnumber2: '87654321',contactemail: 'demo@demo.com',contactdateofbirth: '1970/01/23',contactremark: 'he is a very patient customer'
  },{
    contactsalutation: 'Ms',contactname: 'Jane doly',contactaddress: '123 Some Other Road',contactnumber1: '81234567',contactnumber2: '81234578',contactemail: 'demo@hotmail.com',contactdateofbirth: '1970/02/28',contactremark: 'she is also a very patient customer'
  }
]