Tengo una colección MongoDB (SlopeDay) que tiene fechas almacenadas.
En mi enrutamiento rápido, busco formatear la fecha en MM-DD-AAAA para poder usar eso para la URL. Esa URL encontrará todos los documentos con fechas coincidentes Y resortNames coincidentes.
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); }); }); });No sé cómo hacer esto correctamente. Necesito obtener la ruta para acceder a todos los documentos de SlopeDay que coincidan con las fechas de la URL del parámetro MM-DD-YYYY.
Puedo hacer que funcione dividiendo las cadenas y consultando de esa manera:
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)); });Solo usando Javascript puedo recomendar esta publicación que podría ayudar
De lo contrario, hay muchas bibliotecas que podría usar para hacer esto también. Personalmente, me gusta usar Day.JS. Su función de formato se vería más o menos así y debería ajustarse a tus necesidades y más si quisieras tomar esa ruta.
dayjs(yourDateHere).format('MM-DD-YYYY')
¡salud!