I am currently in the process of transitioning next.js/examples/with-mongodb/util/mongodb.js to TypeScript so I can efficiently cache and reuse my connections to MongoDB within a TypeScript based next.js project. However, I am encountering a TypeScript error regarding cache.promise
that states:
Type 'Promise<MongoClient | { client: MongoClient; db: Db; }>' is not assignable to type 'Promise<MongoClient>'
What is the correct way to declare the mongo property on global in order to satisfy the TypeScript requirements?
import { MongoClient, Db } from "mongodb";
const { DATABASE_URL, DATABASE_NAME } = process.env;
declare global {
namespace NodeJS {
interface Global {
mongo: {
conn: MongoClient | null;
promise: Promise<MongoClient> | null;
};
}
}
}
let cached = global.mongo;
if (!cached) {
cached = global.mongo = { conn: null, promise: null };
}
async function connect() {
if (cached.conn) {
return cached.conn;
}
if (!cached.promise) {
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
cached.promise = MongoClient.connect(DATABASE_URL, opts).then((client) => {
return {
client,
db: client.db(DATABASE_NAME),
};
});
}
cached.conn = await cached.promise;
return cached.conn;
}
export { connect };