When attempting to save a record with the date column into MongoDB using ExpressJS, I noticed that the date part alone is automatically subtracted by one. I am unsure why this is happening. Below you can find the schema of my DB and the post router that I am using.
For example, here is the input posted in the body:
{
"name":"Articulation Exam",
"location":"IoN Center",
"timing":"11:00am",
"date":"06/27/2023",
"maximum_allowed_participants":100,
"active_participants":1
}
Data stored in the database:
{
"_id": "6485a0737cd0de176a0c87c0",
"name": "Articulation Exam",
"location": "IoN Center",
"timing": "11:00am",
"date": "2023-06-26T18:30:00.000Z",
"maximum_allowed_participants": 100,
"active_participants": 1,
"createdAt": "2023-06-11T10:22:43.046Z",
"updatedAt": "2023-06-11T10:22:43.046Z",
"__v": 0
}
As seen in the examples above, the date was posted as 06/27/2023, but it was stored as 2023-06-26 which is incorrect. If there is something I am missing here, please correct me.
router.route('/post').post((req,res)=>{
const data = {
name:req.body.name,
location:req.body.location,
timing:req.body.timing,
date:new Date(req.body.date),
maximum_allowed_participants:req.body.maximum_allowed_participants,
active_participants:req.body.active_participants
}
const newRecord = new Events(data);
newRecord.save()
.then(response=>res.send('A new event "'+response.name+'" has been added successfully!'))
.catch(err=>res.send(err));
})
const eventSchema = new Schema({
name:{
type:String,
required:true,
trim:true,
minlength:3
},
location:{
type:String,
required:true,
trim:true,
minlength:2
},
timing:{
type:String,
required:true,
trim:true,
},
date:{
type:Date,
required:true
},
maximum_allowed_participants:{
type:Number,
required:true
},
active_participants:{
type:Number,
required:true
}
},
{
timestamps:true
});