reactjs - 使用`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;
解决方案
由于您在技术上扩展了全局上下文,因此您需要添加它的新类型。
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
推荐阅读
- python - Python seaborn plot 将数据名称显示为ㅁㅁㅁㅁ。我怎样才能解决这个问题?
- ms-access - 在 MS Access 中使用 SQL 计算多样性指数
- regex - 正则表达式将所有单词截断为最大单词长度?
- javascript - React Native Map View 初始渲染
- python - 如何将 L1 正则化添加到 PyTorch NN 模型?
- vba - 登录后的Http post请求
- c# - C# 数学库(System.Numerics 与 Math.NET)
- asp.net-mvc - 使用 EF Core 3 进行 ASP.NET Core 3 远程验证
- c - C程序不会正确划分两个scanf输入
- javascript - 如何检查用户是否选择了一个属性