I am using Nextjs 13.4 and mongo. I get the following error when I attempt to access the database with a query.:
typeerror SyntaxError: Unexpected token T in JSON at position 0
at GET (webpack-internal:///(sc_server)/./app/api/loadteachers/route.js:19:33)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:242:37)
Here are my files:
route.js
//Fetches the teachers from database.
import {MongoClient} from 'mongodb';
export async function GET()
{
console.log("😃 dbConnect executed.......");
const client = await MongoClient.connect(process.env.MONGODB_CONNECTION_STRING);
const db = await client.db("WDN2");
const teachers = await db.collection('Teachers')
.find()
.sort({_id: -1})
.toArray();
//res.status(200).json({text: teachers});
//console.log("From api route: ", teachers);
//const data = await res.json();
const data = await teachers.json();
client.close();
//return new Response(teachers)
return data
}
Table.jsx
type//load teachers into the table.
"use client";
//import dbConnect from "../../../utils/dbConnect";
async function getStudents(){
console.log("Get students working ........");
const res = await fetch("http://localhost:3000//api/loadteachers");
return res.json();
}
export default async function Table()
//const Table = ()=>
{
//Call api here.
//const dbConnectfunc = await dbConnect();
//console.log("hello this is the table component.");
//console.log(dbConnectfunc);
const data = await getStudents();
console.log(data);
return(
<div >
<table className="table ">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Date</th>
<th scope="col"> First Name</th>
<th scope="col"> Last Name</th>
<th scope = "col"> Email </th>
<th scope = "col"> Classes</th>
<th scope = "col"> Students </th>
<th scope = "col"> Remove</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>5/17/22</td>
<td> megan</td>
<td> jones</td>
<td>mj@gmail.com </td>
<td> 4</td>
<td> 120 </td>
<td> Remove</td>
</tr>
</tbody>
</table>
</div>
)
}
Here is the folder structure:
app
— components
---- Table.jsx
— api
---- loadteachers
---- route.js
Not sure what else to do here.