You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Most of these api routes run await connectDb() before proceeding. Here it is:
import mongoose from 'mongoose';
import config from 'config';
const connectionObject: any = {};
const connectDb = async () => {
if (connectionObject.isConnected) {
return;
}
try {
const db = await mongoose.connect(process.env.MONGODB_URI || config.get('mongoURI'), {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});
connectionObject.isConnected = db.connections[0].readyState;
} catch (err) {
console.log('Failed to connect to db', err);
}
};
export default connectDb;
The issue I'm running into right now, however, is that connectionObject seems to get emptied out for some reason, when different routes are hit.
I can't be sure, but I think that as long as the route that is hit is within the same directory as the previous route that was hit before it, then the connection will not be reinstantiated. So, if I hit login.ts after hitting paginate.ts, a new MongoDB connection will be created. Likewise, if I hit load.ts after login.ts, then a new connection will NOT be created.
I feel like I'm missing something elementary here. What are my options / what am I doing wrong?
I've found a similar Github issue that seems relevant to my problem, but it hasn't helped me. I'm having this issue in dev mode and prod.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I was following this example on NextJS' official Github page, and I've managed to get up and running in my project.
Below is my file structure:
Most of these api routes run
await connectDb()
before proceeding. Here it is:The issue I'm running into right now, however, is that
connectionObject
seems to get emptied out for some reason, when different routes are hit.I can't be sure, but I think that as long as the route that is hit is within the same directory as the previous route that was hit before it, then the connection will not be reinstantiated. So, if I hit
login.ts
after hittingpaginate.ts
, a new MongoDB connection will be created. Likewise, if I hitload.ts
afterlogin.ts
, then a new connection will NOT be created.I feel like I'm missing something elementary here. What are my options / what am I doing wrong?
I've found a similar Github issue that seems relevant to my problem, but it hasn't helped me. I'm having this issue in dev mode and prod.
Stackoverflow link
Beta Was this translation helpful? Give feedback.
All reactions