How to connect mongodb to Nextjs without mongoose?
Unanswered
Mandarin fish posted this in #help-forum
Mandarin fishOP
I am using nextjs 15 app router with mongodb as database.i simply want to fetch data in server component.Here i'm following the official example.
https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
They use this file: mongodb.ts
But they are not telling how to properly connect to db before making a request
They have this testDatabaseConnection() functoin in actions.ts file,which is called in the page.tsx file.So am i supposed to call this function in every page ?
Additional question: 1.Do i need to cache database connection? 2.Will face any problems in production when lot of users connect to the database?
Note:
I don't want to use mongoose because my use case is different.
https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
They use this file: mongodb.ts
import { MongoClient } from "mongodb";
if (!process.env.MONGODB_URI) {
throw new Error('Invalid/Missing environment variable: "MONGODB_URI"');
}
const uri = process.env.MONGODB_URI;
const options = { appName: "devrel.template.nextjs" };
let client: MongoClient;
if (process.env.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).
let globalWithMongo = global as typeof globalThis & {
_mongoClient?: MongoClient;
};
if (!globalWithMongo._mongoClient) {
globalWithMongo._mongoClient = new MongoClient(uri, options);
}
client = globalWithMongo._mongoClient;
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options);
}
// Export a module-scoped MongoClient. By doing this in a
// separate module, the client can be shared across functions.
export default client;
But they are not telling how to properly connect to db before making a request
They have this testDatabaseConnection() functoin in actions.ts file,which is called in the page.tsx file.So am i supposed to call this function in every page ?
Additional question: 1.Do i need to cache database connection? 2.Will face any problems in production when lot of users connect to the database?
Note:
I don't want to use mongoose because my use case is different.
3 Replies
You can first check whether the client is connected or not, there should be some property. if not, you can connect
Additional question: 1.Do i need to cache database connection? 2.Will face any problems in production when lot of users connect to the database?
1. I m unsure but I think this code already handles this; If you're importing the same client
2. as long as you have a dedicated instance, then no