我使用 mongodb 模板安裝了 next.js 應用程式:
npx create-next-app --e with-mongodb my-app
并安裝了 TypeScript。我需要轉換/lib/mongodb.js為 TypeScript
目前它看起來像這樣,幾乎沒有型別變化
// lib/mongodb.ts
import { MongoClient } from 'mongodb'
const uri = process.env.MONGODB_URI
const options = {}
let client
let clientPromise: MongoClient
if (!process.env.MONGODB_URI) {
throw new Error('Please add your Mongo URI to .env.local')
}
if (process.env.NODE_ENV === 'development') {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
export default clientPromise
它在大喊:
請幫我定義正確的型別,我很喜歡 TypeScript!提前致謝!
uj5u.com熱心網友回復:
我昨天遇到了同樣的問題。幸運的是,找到了解決方案!
import { MongoClient } from "mongodb";
if (!process.env.MONGODB_URI) {
throw new Error("Please add your Mongo URI to .env.local");
}
const uri: string = process.env.MONGODB_URI;
let client: MongoClient;
let clientPromise: Promise<MongoClient>;
if (process.env.NODE_ENV === "development") {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
let globalWithMongoClientPromise = global as typeof globalThis & {
_mongoClientPromise: Promise<MongoClient>;
};
if (!globalWithMongoClientPromise._mongoClientPromise) {
client = new MongoClient(uri);
globalWithMongoClientPromise._mongoClientPromise = client.connect();
}
clientPromise = globalWithMongoClientPromise._mongoClientPromise;
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri);
clientPromise = client.connect();
}
// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/417232.html
標籤:
上一篇:聚合函式未顯示計數大于1的結果
下一篇:mongoDB-聚合后按id查找
