Home > database >  error when use Moment.js not accept to save in DB
error when use Moment.js not accept to save in DB

Time:03-15

when I try to use Moment.js in server code and do save action I get this error are there any solution or any alternative to change Date format

{
      stringValue: '"March 15th 2022, 2:28:00 am"',
      messageFormat: undefined,
      kind: 'date',
      value: 'March 15th 2022, 2:28:00 am',
      path: 'transactionTime',
      reason: AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:
        assert.ok(false)
        generatedMessage: true,
        code: 'ERR_ASSERTION',
        actual: false,
        expected: true,
        operator: '=='
      },
      valueType: 'string'
    }
  },
  _message: 'transaction validation failed'
}

Schema

var moment = require('moment');

const Schema = new mongoose.Schema({
    transactionTime: {
        type: Date,
        default: moment().format('MMMM Do YYYY, h:mm:ss a'),
    },
    ...
})

CodePudding user response:

Which type of data have you set on your db for “date”?

CodePudding user response:

I must let the type save in DB as Date and in default: Date.now() or if I use moment in Server code moment().toDate() then change the format after getting the value from DB like this

moment(transaction.transactionTime).format('MMMM Do YYYY, h:mm:ss a')
  • Related