首页 > 解决方案 > 使用`let cached = global.mongoose`时出现Next.js + Typescript + mongoose错误

问题描述

我试图为 Next.js + Typescript 应用程序创建一个缓存的猫鼬连接,但使用:

let cached = global.mongoose;

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null };
}

全球的。猫鼬显示以下错误:

Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017)

编辑: 这是完整的/lib/dbConnect.ts文件

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;

标签: reactjstypescriptmongodbmongoosenext.js

解决方案


由于您在技术上扩展了全局上下文,因此您需要添加它的新类型。

custom.d.ts对于没有类型的包,我通常在根文件夹中有一个。

在你的情况下:

declare global {
  const mongoose: any
}

custom.d.ts另外,不要忘记添加tsconfig.json

{
  "compilerOptions": {...},
  "include": ["...your other files", "custom.d.ts"],
}


Prisma 连接参考:https ://stackoverflow.com/a/69434850/14122260


推荐阅读