I am using mongodb with nextjs application. I am fetching data from mongodb inside getServerSideProps but I have observed it takes 4-5 secs to fetch data and display it on frontend. Any suggestions how can I improve it?
code:
mongodb.js:
import { MongoClient } from 'mongodb'
const uri = process.env.NEXT_PUBLIC_MONGODB_URI;
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
}
let client
let clientPromise
if (!process.env.NEXT_PUBLIC_MONGODB_URI) {
throw new Error('Please add your Mongo URI to .env.local')
}
if (process.env.NEXT_PUBLIC_NODE_ENV === 'development') {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise;
dashboard.js:
export async function getServerSideProps(context) {
const session = await getServerSession(context.req, context.res, authOptions);
if (!session) {
return {
redirect: {
destination: '/login',
permanent: false
}
}
}
const client = await clientPromise;
const db = client.db("mongodb-db");
const testCollection = db.collection("jobs");
const testData = await jobsCollection.find({ userId: '100' }).toArray();
const jobs = JSON.parse(JSON.stringify(testData));
// Sort the jobs based on timestamp
// Run a loop over all the sorted jobs i.e extract specific key/value pairs and return the data
return {
props: propsData
}
}
In my case I think that the slowness issue is related to mongodb connection or cold start of vercel serverless functions. Because in monogdb atlas it is showing me query command takes 300-500ms so I don’t think that fetching 500-1k array of objects from mongodb is an issue here. If it is related to connections how can I improve performance? Do I need to close the cursor after fetching data from mongodb? Something like this: proper use of mongo db in Next.js · Discussion #12229 · vercel/next.js · GitHub
Any suggestions? Thanks