I’m using nextjs 13.4 and I’m trying to access the mong0 database. I keep getting an error (see images). I’ve narrowed the problem down to the the import statement in my dbConnect…js file:
import {MongoClient, ServerApiVersion } from 'mongodb';
When this is commented out everything works fine. Any ideas on what this could be?
Error:
./node_modules/mongodb/lib/cmap/auth/gssapi.js (4:0)
Module not found: Can't resolve 'dns'
https://nextjs.org/docs/messages/module-not-found
Import trace for requested module:
./node_modules/mongodb/lib/index.js
./utils/dbConnect.js
./components/Admin/Table.jsx
./app/admin/page.jsx
Files:
dbConnect
import {MongoClient, ServerApiVersion } from 'mongodb';
let isConnected = false;
// const client = new MongoClient(process.env.MONGODB_CONNECTION_STRING, {
// serverApi: {
// version: ServerApiVersion.v1,
// strict: true,
// deprecationErrors: true,
// }
// }
// );
export default async function dbConnect(){
console.log("Connecting to db!");
// if(isConnected)
// {
// console.log("MongoDB is already connected");
// return;
// }
// try {
// await client.connect();
// await client.db(process.env.MONGODB_DATABASE_NAME).command({ ping: 1 });
// console.log("😃 dbConnect executed.......");
// isConnected = true;
// }
// catch (error) {
// console.log("ERROR: " + error);
// }
// finally {
// await client.close();
// }
}
Table.jsx
//load teachers into the table.
import dbConnect from "../../utils/dbConnect";
// "use client";
async function getStudents(){
const res = await fetch("https://jsonplaceholder.typicode.com/posts");
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> Bob </td>
<td>Johnson</td>
<td> bj@gmail.com </td>
<td> 4</td>
<td> 120 </td>
<td> Remove</td>
</tr>
</tbody>
</table>
</div>
)
}
package.json
{
"name": "wdn",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"axios": "^1.4.0",
"bootstrap": "^5.2.3",
"bootstrap-icons": "^1.10.5",
"eslint": "8.41.0",
"eslint-config-next": "13.4.3",
"i": "^0.3.7",
"jquery": "^3.7.0",
"mongodb": "^5.5.0",
"next": "13.4.3",
"popper.js": "^1.16.1",
"react": "18.2.0",
"react-bootstrap": "^2.8.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"tailwindcss": "^3.3.2"
}
}