4

I come from the java world and I'm starting in NodeJS. I'm having a hard time understanding how to work with dates and times in NodeJS.

Only dates and only hours.

Here is an example:

export interface teste extends mongoose.Document {
    description: string,
    dateTest: ????,
    openingTime: ????,
    finalTime: ????,
    dateTimeRecord: ????
}

const testeSchema = new mongoose.Schema({
    description:{
        type: String,
        required: true,
        maxlength: 200,
        minlength: 3
    },
    dateTest:{
        type: ?????,
        required: true
    },
    openingTime:{
        type: ?????,
        required: true
    },
    finalTime:{
        type: ?????,
        required: true
    },
    dateTimeRecord:{
        type: ?????,
        required: true
    }
}

export const Teste = mongoose.model<Teste>('Teste', testeSchema)

In all the places I left ????? I don't know what to put.

  • In the dateTest I need to record only dates, without the hours.
  • In the openingTime and finalTime I need to store only hours, no dates.
  • In the dateTimeRecord I need to store the moment that something happened (date and time).

How to do this?

Rafael Bomfim
  • 59
  • 1
  • 6

3 Answers3

1

Mongoose has a Date type. (Docs here) Replace the ??? with Date and you should be all set.

Rastalamm
  • 1,712
  • 3
  • 23
  • 32
1

in Mongoose you have a type of Date you can set a default date (Actually it uses ISODate) you can code it like this

const testeSchema = new mongoose.Schema({
    description:{
        type: String,
        required: true,
        maxlength: 200,
        minlength: 3
    },
    dateTest:{
        type: Date,
        default:Date.now // this sets the default date time stamp using proper ISODate format
        required: true
    },
    openingTime:{
        type: Date,
        required: true
    },
    finalTime:{
        type: Date,
        required: true
    },
    dateTimeRecord:{
        type: Date,
        required: true
    }
}

you can read more in the mongoose documentation here

ALPHA
  • 1,135
  • 1
  • 8
  • 18
  • `default: Date.now` will set the date to the time the app starts. You should use `default: () => Date.now` to set it to the time the document was inserted. – borislemke Sep 19 '22 at 10:12
1

Just setting

field {
   type: Date,
   default: Date.now
}

did not work for me, using typescript. The error pointed out that Date.now returns a number while a Date would be expected.

This did the trick:

field {
   type: Date,
   default: () => new Date(Date.now())
}
Christopher Gertz
  • 1,826
  • 1
  • 15
  • 9