Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js + Typescript + mongoose error when using `let cached = global.mongoose`

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;
like image 941
asobirov Avatar asked Jan 20 '26 07:01

asobirov


1 Answers

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

like image 114
Alisson Leal Avatar answered Jan 23 '26 00:01

Alisson Leal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!