0

I'm using csvtojson npm package to import csv data to mongodb and I'm getting ValidationError: Contact validation failed: contactdateofbirth: Cast to date failed for value "Invalid Date" at path "contactdateofbirth", dayoftheyear: Cast to Number failed for value "NaN" at path "dayoftheyear" error.

Here is what I have done so far:

[
  {
    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()
        })
      })

Here is the short version of the schema:

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

I tried to use new Date but failed to cast to proper date. What am I missing here? Many thanks in advance and greatly appreciate any helps. Thanks again.

Nat
  • 679
  • 1
  • 9
  • 24

1 Answers1

1

I know where I have missed> It was the date format in the 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'
  }
]
Nat
  • 679
  • 1
  • 9
  • 24