Express/MongoDB 日期格式匹配 req.params 到 mongo 文档中的日期

Express/MongoDB date formatting to match req.params to date in mongo document

我有一个 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);
      });
    });
});

我不知道如何正确地执行此操作。我需要获取路径来访问所有与 MM-DD-YYYY 参数 URL.

匹配日期的 SlopeDay 文档

就用Javascript我可以推荐this post that might help

否则,您也可以使用许多库来执行此操作。我个人喜欢使用 Day.JS。他们的 format function 它看起来像这样,如果您想走那条路,应该可以满足您的需求甚至更多。

dayjs(yourDateHere).format('MM-DD-YYYY')

干杯!

我可以通过分解字符串并以这种方式查询来让它工作:

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));
});