How to connect the MongoDB database in my next.js app by Mongoose with instrumentation.js
Unanswered
Manik Islam Mahi posted this in #help-forum
I have tried like this,
It's working fine. But after using the following middleware, I face this error when I go to the About page.
Here is my middleware,
// dbConfig.js
import mongoose from "mongoose";
const MONGODB_URI = process.env.MONGO_URI;
if (!MONGODB_URI) {
throw new Error(
"Please define the MONGODB_URI environment variable inside .env.local"
);
}
let cached = global.mongoose;
if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}
export async function dbConnect() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
bufferCommands: false,
};
cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
console.log("Db connected");
return mongoose;
});
}
try {
cached.conn = await cached.promise;
} catch (e) {
cached.promise = null;
throw e;
}
return cached.conn;
}
// /instrumentation.js
import { dbConnect } from "./config/dbConfig";
export async function register() {
await dbConnect();
}
It's working fine. But after using the following middleware, I face this error when I go to the About page.
Runtime Error
TypeError: An error occurred while loading instrumentation hook: {imported module [project]/nodemodules/mongoose/dist/browser.umd.js [instrumentation] (ecmascript)}.default.connect is not a function
Call Stack
4
dbConnect
.next\server\edge\chunks\_43c91674._.js (32:189)
Module.register
.next\server\edge\chunks\_43c91674._.js (57:148)
registerInstrumentation
.next\server\edge\chunks\_fc2ffb57._.js (27:35)
async adapter
.next\server\edge\chunks\_fc2ffb57._.js (6169:5)
Here is my middleware,
// middleware.js
import { NextResponse } from "next/server";
export function middleware(request) {
return NextResponse.redirect(new URL("/", request.url));
}
export const config = {
matcher: "/about/:path*",
};