If a Mongoose schema has a type of Date and you are using a <input type="date">
to allow the user to enter/select a date, the actual date stored in the database will be one day earlier than specified.
This is because of the way JavaScript's Date() class/constructor, which Mongoose uses to convert a string value into a data object, incorrectly sets the date if the string is in the YYYY-MM-DD
format. You can demo this by typing new Date('2025-01-29')
in the console - the returned date will be yesterday. Interestingly, new Date('01/29/2025')
or even new Date('1-29-2025')
do not suffer from this bug.
The most straightforward fix is to append T00:00
(designate the time) to the end of the date string. Try it in the console: new Date('2025-01-29T00:00')
. You can code the fix in either the front or the backend (controller), for example:
async function create(req, res) {
try {
req.body.user = req.user._id;
// Date fix
req.body.expiration += 'T00:00';
const post = await Post.create(req.body);
res.json(post);
} catch (err) {
res.status(400).json({ message: 'Post create failed' })
}
}
Note that using a date/time works as expected.