首页 > 解决方案 > mongoose.connect 错误 TS2531:对象可能为“空”

问题描述

我有一个内置在 typescript 中的 node/express/mongoose 应用程序。但是我对猫鼬有疑问。

TS2531: Object is possibly 'null'.使用猫鼬时出现以下错误错误。

应用程序.ts

import express from 'express';
import logger from 'morgan';
import mongoose from 'mongoose';
import passport from 'passport';
import cors from "cors";

import Routes from './routes';
import Config from './config/config';

class App {

    public app: express.Application;
    public config: any;

    constructor() {

        this.app = express();

        this.environment();
        this.database();
        this.middleware();
        this.routes();

    }

    private environment(): void {

        this.config = new Config();

    }

    private database(): void {

        const uri: string = this.config.db.uri;
        const options: any = this.config.db.options;

            mongoose.connect(uri, options).then(

                () => {
                    console.log("MongoDB Successfully Connected On: " + this.config.db.uri)
                },
                (err: any) => {
                    console.error("MongoDB Error:", err);
                    console.log('%s MongoDB connection error. Please make sure MongoDB is running.');
                    process.exit();
                }

            );

    }

    private middleware(): void {

        this.app.use(cors());
        this.app.use(logger('dev'));
        this.app.use(express.json());
        this.app.use(express.urlencoded({ extended: true }));
        this.app.use(passport.initialize());

    }

    private routes(): void {

        const routes = new Routes(this.app);

    }

}

export default App;

我该如何正确处理这个?

编辑

发布整个应用程序文件以提供更多上下文。该错误特别指出了以下行mongoose.connect(uri, options)

src/app.ts:39:13 - 错误 TS2531:对象可能为“空”。

39 mongoose.connect(uri, options).then( ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

标签: node.jstypescriptmongoose

解决方案


函数定义connect

export function connect(uris: string, options: ConnectionOptions, callback: (err: mongodb.MongoError) => void): null;
export function connect(uris: string, callback: (err: mongodb.MongoError) => void): null;
export function connect(uris: string, options?: ConnectionOptions): Promise<Mongoose>;

返回 a 的唯一重载Promise是最后一个重载,其他重载显式返回null。由于options在您的代码中键入 as any,第二个参数可以匹配最后两个重载中的任何一个,并且由于第一个匹配是返回 null 的那个,编译器选择接受回调并返回 null 的那个。

最简单的解决方案是强制options转换为mongoose.ConnectionOptions或键入options以下内容mongoose.ConnectionOptions

mongoose.connect(uri, options as mongoose.ConnectionOptions).then( … )

推荐阅读