I have a MongoDB collection (SlopeDay) that has dates stored.
In my express routing, I’m looking to format the date to MM-DD-YYYY so that I can use that for the URL. That URL will find all documents with matching dates AND matching resortNames
.
dateRouter.get("/:formattedDate", (req, res) => {
const formattedDate = req.params.formattedDate;
SlopeDay.find({}) // isolate dates
.then((dateObj) => {
dateObj.forEach((date, i) => {
let dateStr =
// MM-DD-YYYY reformatting to string
("0" + (date.date.getMonth() + 1)).slice(-2) +
"-" +
("0" + date.date.getDate()).slice(-2) +
"-" +
date.date.getFullYear();
// map below doesn't seem to be doing much
const objWithFormattedDate = dateObj.map((obj) => {
return { ...obj, formattedDate: dateStr, isNew: true };
});
// console.log(objWithFormattedDate);
});
});
});
I’m at a loss for how to do this properly. I need the get route to access all SlopeDay documents matching dates to the MM-DD-YYYY parameter URL.
2
Answers
I'm able to get it working by breaking the strings up and querying that way:
Just using Javascript I can recommend this post that might help
Otherwise, there are many libraries you could use to do this as well. Personally I like using Day.JS. Their format function it would look something like this and should fit your needs and more if you wanted to take that route.
dayjs(yourDateHere).format('MM-DD-YYYY')
cheers!