Home > Blockchain >  Next.js Typescript mongoose error when using `let cached = global.mongoose`
Next.js Typescript mongoose error when using `let cached = global.mongoose`

Time:10-17

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;

CodePudding user response:

I don't see anything particularly wrong in your file, maybe check if your file is in the right directory, also your .env.local file.

This is the lib/dbConnect.js I used in my previous project just for your reference.

import mongoose from 'mongoose';

const MONGODB_URI = 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 = {
      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
}

export default dbConnect

CodePudding user response:

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

  • Related