I am trying to integrate mongodb
within my NextTS app but I am having an issue and I can not figure it out.
What I did so far:
I created the two process variables MONGODB_URI
and MONGODB_DB
I created mongodb.ts
under the utils
folder, with the following contents that I took from https://github.com/vercel/next.js/blob/canary/examples/with-mongodb/util/mongodb.js :
import { MongoClient } from "mongodb";
const MONGODB_URI = process.env.MONGODB_URI;
const MONGODB_DB = process.env.MONGODB_DB;
if (!MONGODB_URI) {
throw new Error("Please define the MONGODB_URI environment variable inside .env.local");
}
if (!MONGODB_DB) {
throw new Error("Please define the MONGODB_DB environment variable inside .env.local");
}
/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentially
* during API Route usage.
*/
let cached = global.mongo;
if (!cached) {
cached = global.mongo = { conn: null, promise: null };
}
export async function connectToDatabase() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => {
return {
client,
db: client.db(MONGODB_DB),
};
});
}
cached.conn = await cached.promise;
return cached.conn;
}
Just to try it out, I have tried with the example project (which is just JS), and it is working just fine yarn create next-app --example with-mongodb with-mongodb-app
When I start the app, this is where it breaks as far as the log goes:
yarn run v1.22.10
$ next dev
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info - Using webpack 5. Reason: no custom webpack configuration in next.config.js https://nextjs.org/docs/messages/webpack5
error - ./node_modules/mongodb/lib/core/auth/gssapi.js:2:0
Module not found: Can't resolve 'dns'
null
And after a save in a file, so that it tries to recompile:
wait - compiling...
info - Using external babel configuration from C:\Users\Darkbound\Desktop\Inventory-ReactTS\.babelrc
error - ./node_modules/mongodb/lib/core/auth/gssapi.js:2:0
Module not found: Can't resolve 'dns'
null