Home > database >  Typescript is throwing a type error when using global.mongoose
Typescript is throwing a type error when using global.mongoose

Time:09-22

I'm trying to implement chaching to my database connection file, for my next.js app so I won't have to go through the connection process all over again when I interact with the database.

import mongoose from 'mongoose';

const uri: string = process.env.MONGO_URI!

But after adding the following line of code, when I hover on mongooseI keep getting the "Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.ts(7017)" error and I couldn't figure out why.

let cached = global.mongoose

Just a note, before adding the line above there was no error in the file

const opts: object = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    bufferCommands: false,

}
const connecter = () => {
    console.log(typeof globalThis.mongoose)
    mongoose.connect(uri, opts).then(mongoose => {
        return console.log('Database connection established')
    })
}
export default connecter

CodePudding user response:

You may refer to link: Create a global variable in TypeScript.

define mongoose connection instance in the globalObject explicity.

import { Connection } from "mongoose";

declare module NodeJS {
  interface Global {
    mongoose: Connection
  }
}
  • Related