我有一个存储日期的MongoDB集合(SlopeDay)。

在我的快速路由中,我希望将日期格式化为MM-DD-YYYY,这样我就可以将其用于URL。该URL将找到所有具有匹配日期和匹配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);
});
});
});我对如何做好这件事感到不知所措。我需要get路由访问所有的SlopeDay文档匹配日期的MM-DD-YYYY参数URL。
发布于 2022-04-22 02:25:10
我可以通过解锁和查询的方式让它正常工作:
dateRouter.get("/:formattedDate", (req, res) => {
const formattedDate = req.params.formattedDate;
// break up the date
const targetChars = formattedDate.substring(3, 5);
const beforeTargetChar = formattedDate.substring(0, 3);
const afterTargetChar = formattedDate.substring(5);
// create lower and upper boundaries that straddle the formatted date
const lowerbound = beforeTargetChar + (targetChars - 1) + afterTargetChar;
const upperbound =
beforeTargetChar + (Number(targetChars) + 1) + afterTargetChar;
SlopeDay.find({
date: {
// find docs with dates between the boundaries (THIS SHOULD EQUAL req.params.formattedDate)
$gte: new Date(lowerbound),
$lt: new Date(upperbound),
}, // add 2nd query here
}).then((dateData) => res.send(dateData));
});发布于 2022-04-22 00:24:38
只要使用Javascript,我可以推荐这篇文章也许能帮上忙
否则,您也可以使用许多库来完成此操作。就我个人而言,我喜欢使用Day.JS。他们的格式函数看起来会像这样,如果你想走这条路的话,应该能满足你的需求。
dayjs(yourDateHere).format('MM-DD-YYYY')
干杯!
https://stackoverflow.com/questions/71961836
复制相似问题