I was trying to created a cached mongoose connection for Next.js + Typescript app, but using:
let cached = global.mongoose;
if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}
global.mongoose is showing the following Error:
Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017)
EDIT:
here's full /lib/dbConnect.ts file
import mongoose, { Connection } from "mongoose";
const MONGODB_URI: string = process.env.MONGODB_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 };
}
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) => {
return mongoose;
});
}
cached.conn = await cached.promise;
return cached.conn;
}
export default dbConnect;
Since you're technically extending the global context, you need to add its new types.
I usually have a custom.d.ts in the root folder for packages that don't have types.
In your case:
declare global {
const mongoose: any
}
Also, don't forget to add custom.d.ts in tsconfig.json:
{
"compilerOptions": {...},
"include": ["...your other files", "custom.d.ts"],
}
reference with Prisma connection: https://stackoverflow.com/a/69434850/14122260
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With