Answer the question
In order to leave comments, you need to log in
Why is MongoDB connection cached in Next.js?
I am learning Next.js. And I noticed that the connection to the database is often cached. For example, like this:
let cachedClient = null;
let cachedDb = null;
export async function connectToDatabase() {
if (cachedClient && cachedDb) {
return {
client: cachedClient,
db: cachedDb,
};
}
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
let client = new MongoClient(MONGODB_URI, opts);
await client.connect();
let db = client.db(MONGODB_DB);
cachedClient = client;
cachedDb = db;
return {
client: cachedClient,
db: cachedDb,
};
}
let cached = global.mongoose
if (!cached) {
cached = global.mongoose = { conn: null, promise: null }
}
async function dbConnect () {
if (cached.conn) {
return cached.conn
}
if (!cached.promise) {
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
bufferCommands: false,
bufferMaxEntries: 0,
useFindAndModify: true,
useCreateIndex: true
}
cached.promise = mongoose.connect(MONGODB_URI, opts).then(mongoose => {
return mongoose
})
}
cached.conn = await cached.promise
return cached.conn
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question