In a nextJs project connected to mongoDB, I have multiple database connection in multiple getStaticProps and getStaticPaths functions.
The code works but is repeating multiple times in my project :
const client = await MongoClient.connect('mongodb+srv://xxxxxxxx')
const db = client.db()
const meetupsCollection = db.collection('meetups')
const result = await meetupsCollection.insertOne(something) //or any other db method
client.close()
I would like to refactor this code and just create a helper/dbConnect.js folder with the code bellow, but when I import and deploy mongoConnect() to the rest of the code, it doesn't work.
// /helper/mongoConnect.js
import {MongoClient} from 'mongodb'
const mongoConnect = async () => {
const client = await MongoClient.connect('mongodb+srv://xxxxx')
const db = client.db()
const meetupsCollection = db.collection('meetups')
return meetupsCollection
}
export default mongoConnect
// /pages/index.js
import mongoConnect from '../helper/mongoConnect'
/* here is my page component*/
export const getStaticProps = async () => {
const meetupsCollection = await mongoConnect()
const meetups = await meetupsCollection..insertOne(something) //or any other db method
client.close()
return {
props: {
...
})),
},
revalidate: 10,
}
}
Where should I put this helper file without exposing anything to client? /pages? /api? If I put it in my project root /, I have error messages (dns, net, tls, fs,...) like:
Failed to compile
./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
./pages/index.jsx
Thanks in advance