tournaments ordered by date

This commit is contained in:
Owen Rees
2023-05-23 10:00:43 +02:00
parent 8b8bf9dcb6
commit e0d363e612
6 changed files with 3904 additions and 24 deletions
+35 -9
View File
@@ -1,13 +1,39 @@
import type { NextApiRequest, NextApiResponse } from 'next'
import type { NextApiRequest, NextApiResponse } from "next";
import clientPromise from "@/lib/mongodb";
export async function GET(req: NextApiRequest, res: NextApiResponse) {
try {
const client = await clientPromise
const db = client.db("tournamentsFranceDB")
const data = await db.collection("tournaments").find({}).toArray()
return new Response(JSON.stringify(data), { status: 200 })
} catch (error) {
return new Response(JSON.stringify(error), { status: 500 })
}
// TODO delete req / res ?
try {
const client = await clientPromise;
const db = client.db("tournamentsFranceDB");
// const data = await db.collection("tournaments").find({}).toArray();
// converts date from string into a date and then orders by date
const data = await db
.collection("tournaments")
.aggregate([
{
$addFields: {
dateParts: {
$dateFromString: {
dateString: "$date",
format: "%d/%m/%Y",
},
},
},
},
{
$sort: {
dateParts: 1,
},
},
{
$unset: "dateParts",
},
])
.toArray();
return new Response(JSON.stringify(data), { status: 200 });
} catch (error) {
return new Response(JSON.stringify(error), { status: 500 });
}
}