Skip to content
Advertisement

date in moment.js does not change when submit new transaction still save last date until refresh server

I am using moment.js to format date and save it in DB

Schema code

const Schema = new mongoose.Schema({
    transactionTime: {
        type: Date,
        default: moment().toDate(),
    },

front code

<td>{moment(transaction.transactionTime).format('MMMM Do YYYY, h:mm:ss a')}</td>

but when I submit a transaction the date is not updated for real-time I send it I must refresh the server to update the date

enter image description here

Advertisement

Answer

When using moment().toDate() as the default, the default value is set to the date and time when you started the application and stays constant. What you want to do is to rather specify a function that returns the current date, which would result in the function being executed at each insertion, thus getting the actual current time:

const Schema = new mongoose.Schema({
    transactionTime: {
        type: Date,
        default: () => moment().toDate(),
    },
...
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement