https://www.mongodb.com/developer/how-to/nextjs-with-mongodb/
the tutorial is great, except it is missing the util/mongodb file
any suggestions?
https://www.mongodb.com/developer/how-to/nextjs-with-mongodb/
the tutorial is great, except it is missing the util/mongodb file
any suggestions?
here is the directory structure of the import:
drwxrwxr-x 1 rwhitney rwhitney 4096 Mar 19 22:19 .
drwxrwxr-x 1 rwhitney rwhitney 4096 Mar 19 22:19 …
-rw-rw-r-- 1 rwhitney rwhitney 12 Mar 19 09:49 .env.local.example
drwxrwxr-x 1 rwhitney rwhitney 4096 Mar 19 22:19 .git
-rw-rw-r-- 1 rwhitney rwhitney 362 Mar 19 09:49 .gitignore
drwxrwxr-x 1 rwhitney rwhitney 4096 Mar 19 22:19 lib
drwxrwxr-x 1 rwhitney rwhitney 4096 Mar 19 22:19 node_modules
-rw-rw-r-- 1 rwhitney rwhitney 241 Mar 19 09:49 package.json
-rw-rw-r-- 1 rwhitney rwhitney 34619 Mar 19 22:19 package-lock.json
drwxrwxr-x 1 rwhitney rwhitney 4096 Mar 19 22:19 pages
drwxrwxr-x 1 rwhitney rwhitney 4096 Mar 19 22:19 public
-rw-rw-r-- 1 rwhitney rwhitney 3610 Mar 19 09:49 README.md
as you can see, there is no util dir and thus, no mongodb file
Nevermind I found the solution
Please share the solution so others ending up with the same issue know what to do.
SOLUTION:
create the folder util in the root
add the following to the file you also create called mongodb.js:
import { MongoClient } from 'mongodb';
const MONGODB_URI = process.env.MONGODB_URI;
const MONGODB_DB = process.env.MONGODB_DB;
// check the MongoDB URI
if (!MONGODB_URI) {
throw new Error('Define the MONGODB_URI environmental variable');
}
// check the MongoDB DB
if (!MONGODB_DB) {
throw new Error('Define the MONGODB_DB environmental variable');
}
let cachedClient = null;
let cachedDb = null;
export async function connectToDatabase() {
// check the cached.
if (cachedClient && cachedDb) {
// load from cache
return {
client: cachedClient,
db: cachedDb,
};
}
// set the connection options
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
// Connect to cluster
let client = new MongoClient(MONGODB_URI, opts);
await client.connect();
let db = client.db(MONGODB_DB);
// set cache
cachedClient = client;
cachedDb = db;
return {
client: cachedClient,
db: cachedDb,
};
}
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.