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



我试图为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;

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

对于没有类型的包,我通常在根文件夹中有一个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

我没有在您的文件中看到任何特别错误的地方,也许可以检查您的文件是否在正确的目录中,也检查您的.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

作为棱镜链接:

创建一个新文件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

未测试

快速简便的解决方案

这个连接文件基于GitHub上的一个官方Next.Js示例。

该项目能够使用mongoose库连接到mongodb。然而,他没有提供如何在TypeScript中实现这一点的示例。但是,您可以很容易地转换正常工作的示例代码,而无需在utils/global.d.ts等中声明类型

1首先安装猫鼬及其口味

为了安装";猫鼬;在Next.js中的TypeScript项目中,请执行以下步骤:

1-打开项目根目录下的终端。

2-运行以下命令安装";猫鼬":

# if you are using npm
npm install mongoose
# if you are using yarn
yarn add mongoose

3-运行下面的命令;猫鼬;类型:

# 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;

在Alisson Leal的回答中,声明猫鼬如下似乎对我有效:

// the namespace conflicts, so import as 'mg'
import { default as mg } from 'mongoose';
declare global {
var mongoose: {
conn: null | typeof mg;
promise: null | Promise<typeof mg>;
};
}

相关内容

  • 没有找到相关文章

最新更新