Reputation: 2753
Below is my mongoose Schema out of which createdOn is of type date and default to Date.now().
const SurveyResponseModel = mongoose.Schema({
surveyId: { type: String, required: true },
surveyData: [surveyData],
result : [respResult],
patientId: { type: String },
surveyBy: {type: String},
createdOn: { type: Date, default: Date.now() },
});
Here is how I'm adding new entries to the db.
const newSurvey = new surveyResponseModel({ surveyId, surveyData, surveyBy, patientId, result })
let savedSurvey = await newSurvey.save();
Up until here everything works fine. The problem starts when new entries are made into the schema. I get the same timestamp of createdOn for each new entries.
What am I doing wrong? Is it createdOn: { type: Date, default: Date.now() }
a issue or something else. Is it a problem with MongoDB or my node express server? Some help and feedback would really be appreciated.
Upvotes: 1
Views: 646
Reputation: 81
When this code is executed (at server startup), Date.now()
is executed and the result is saved in the object literal, hence that single timestamp will be used for the duration of the server's life.
Try passing the function instead of a value it returns at a single point in time. Mongoose will then call it at runtime.
createdOn: { type: Date, default: Date.now }
Upvotes: 2