mongoose.connect错误TS2531:对象可能为'null'

时间:2018-06-27 15:28:08

标签: node.js typescript mongoose

我有一个内置打字稿的node / express / mongoose应用程序。但是我遇到猫鼬问题。

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

app.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:对象可能为'null'。

     

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

2 个答案:

答案 0 :(得分:4)

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>;

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

最简单的解决方案是将options强制转换为mongoose.ConnectionOptions或将options键入为mongoose.ConnectionOptions,以开始:

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

答案 1 :(得分:0)

显然mongoose.connect()可以返回null,并且您的TypeScript已配置为进行严格的空性检查(这是一件好事!),因此您需要“发誓”添加非零感叹号:

mongoose.connect(uri, options)!.then(...

但是,如果返回值 恰好是null,则会在运行时崩溃。