我試圖為 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;
uj5u.com熱心網友回復:
由于您在技術上擴展了全域背景關系,因此您需要添加其新型別。
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
uj5u.com熱心網友回復:
我在你的檔案中沒有看到任何特別錯誤的地方,也許檢查你的檔案是否在正確的目錄中,還有你的.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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/326704.html
上一篇:我可以實作進入參考嗎
下一篇:如何組合多個NumPy布爾陣列?
