Anselum
Anselum

Reputation: 5

Global keyword error, while connecting to mongoose

I'm trying to connect my nextjs app with MongoDB using mongoose, and I created this mongodb.ts file, which creates a connection with the DB, and returns the cached connection if available, and when I try to build my project this error arises.

import mongoose from "mongoose";

declare global {
    var mongoose: { conn: any, promise: any };
}

const MONGODB_URI = process.env.MONGODB_URI;


let cached = global.mongoose;

if (!cached) {
    cached = global.mongoose = { conn: null, promise: null };
}


async function connectToDatabase() {
    if (cached.conn) return cached.conn;

    if (!MONGODB_URI) {
        throw new Error("Please define the MONGODB_URI environment variable inside .env.local");
    }

    if (!cached.promise) {
        cached.promise = mongoose.connect(MONGODB_URI).then((mongoose) => mongoose);
    }

    cached.conn = await cached.promise;
    return cached.conn;
}

export default connectToDatabase;

Error

Failed to compile.

./lib/mongodb.ts
4:2  Error: Unexpected var, use let or const instead.  no-var
4:24  Error: Unexpected any. Specify a different type.  @typescript-eslint/no-explicit-any
4:38  Error: Unexpected any. Specify a different type.  @typescript-eslint/no-explicit-any

Note I don't want to disable the eslint, and I'm using Nextjs 15, React 19 with Typescript.

Upvotes: 0

Views: 34

Answers (0)

Related Questions