使用`let cached = global.mongoose`时出现Next.js + Typescript + mongoose错误

hts6caw3  于 2023-03-29  发布在  Go
关注(0)|答案(4)|浏览(101)

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

let cached = global.mongoose;

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

global.mongoose显示以下错误:
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;
k3bvogb1

k3bvogb11#

由于您在技术上扩展了全局上下文,因此需要添加它的新类型。
对于没有类型的包,我通常在根文件夹中有一个custom.d.ts
在您的情况下:

declare global {
  const mongoose: any
}

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

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

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

x8diyxa7

x8diyxa72#

作为Prisma链接:
创建新文件utils/global.d.ts

import { Connection } from 'mongoose'

declare global {
    var mongoose: any
}

export const mongoose = global.mongoose || new Connection()

if (process.env.NODE_ENV !== 'production') global.mongoose = mongoose

在tsconfig.json中添加以包含:

...
"include": ["next-env.d.ts", "utils/global.d.ts", "**/*.ts", "**/*.tsx"],
...

dbConnect.js:

import mongoose 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'
    )
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections growing exponentially
 * during API Route usage.
 */
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

未测试

ef1yzkbh

ef1yzkbh3#

快速简单的解决方案!

此连接文件基于official Next.Js example on GitHub
该项目可以使用mongoose库连接到mongodb。但是,他没有提供如何在TypeScript中实现这一点的示例。但是,您可以轻松地转换示例代码,该代码将正常工作,而无需在utils/global.d.ts等中声明类型。

1首先安装mongoose及其flavors。

要在Next.js中的TypeScript项目中安装“mongoose”,请执行以下步骤:
1 -打开项目根目录下的终端。
2 -运行以下命令安装“mongoose”:

# if you are using npm
npm install mongoose

# if you are using yarn
yarn add mongoose

3 -运行以下命令安装“mongoose”类型:

# se estiver usando npm
npm install --save-dev @types/mongoose

# se estuver usando yarn
yarn add --dev @types/mongoose

2创建TypeScript连接文件dbConnect.ts

import mongoose from 'mongoose';

const MONGODB_URI: string | any = process.env.MONGODB_URI;

if (!MONGODB_URI) {
  throw new Error('Please define the MONGODB_URI environment variable inside .env.local');
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections growing exponentially
 * during API Route usage.
 */
let cached = (global as any).mongoose;

if (!cached) {
  cached = (global as any).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) => {
      console.log('Connected to database!');
      return mongoose;
    });
  }

  try {
    cached.conn = await cached.promise;
  } catch (e) {
    cached.promise = null;
    throw e;
  }

  return cached.conn;
}

export default dbConnect;
kse8i1jr

kse8i1jr4#

我没有看到你的文件有什么特别的错误,也许检查一下你的文件是否在正确的目录下,还有你的.env.local文件。
这是我在以前的项目中使用的lib/dbConnect.js,仅供参考。

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

相关问题