【问题标题】:Typescript is throwing a type error when using global.mongoose打字稿在使用 global.mongoose 时抛出类型错误
【发布时间】:2021-11-13 11:46:54
【问题描述】:

我正在尝试为我的 next.js 应用程序实现对我的数据库连接文件的 chaching,因此当我与数据库交互时,我不必重新执行连接过程。

import mongoose from 'mongoose';

const uri: string = process.env.MONGO_URI!

但添加以下代码行后,当我将鼠标悬停在 mongoose 上时,我不断收到 “元素隐式具有 'any' 类型,因为类型 'typeof globalThis' 没有索引 signature.ts(7017)” 错误,我不知道为什么。

let cached = global.mongoose

请注意,在添加上面的行之前,文件中没有错误

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

【问题讨论】:

    标签: node.js typescript mongoose


    【解决方案1】:

    您可以参考链接:Create a global variable in TypeScript

    在 globalObject 中明确定义猫鼬连接实例。

    import { Connection } from "mongoose";
    
    declare module NodeJS {
      interface Global {
        mongoose: Connection
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-18
      • 2018-08-12
      • 1970-01-01
      • 2022-01-19
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多