ARTICLE AD BOX
I am trying to create a reusable MongoDB connection function using Mongoose in a Node.js / Next.js project with TypeScript.
To prevent multiple connections during hot reload, I am caching the connection on the global object.
However, I am getting a type error on the line where I assign mongoose.connect() to the cached promise.
Error:
Type 'Promise<typeof import("mongoose")>' is not assignable to type 'Promise<{ conn: ... | null; promise: Promise<...> | null; }>'. Type 'typeof import("mongoose")' is missing the following properties from type '{ conn: ... | null; promise: Promise<...> | null; }': conn, promiseconnectDB code:
import mongoose from "mongoose"; const MONGO_URI = process.env.MONGO_URI; if (!MONGO_URI) throw new Error("Mongo db url not define."); let cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; }; export const connectDB = async () => { if (cached.conn) return cached.conn; if (!cached.promise) { cached.promise = mongoose.connect(MONGO_URI); } try { cached.conn = await cached.promise; } catch (error) { cached.promise = null; throw error; } return cached.conn; };global.d.ts
import mongoose from "mongoose"; declare global { var mongoose: { conn: typeof mongoose | null; promise: Promise<typeof mongoose> | null; }; };I expected the types to match because mongoose.connect() returns Promise<typeof mongoose>.
What is the correct way to type a cached mongoose connection stored on the global object in TypeScript?
Any help would be appreciated.
