【问题标题】:mongoose.connect error TS2531: Object is possibly 'null'mongoose.connect 错误 TS2531:对象可能为“空”
【发布时间】:2018-06-28 00:14:01
【问题描述】:

我有一个内置在 typescript 中的 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:对象可能为“空”。

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

【问题讨论】:

  • 你在哪一行得到错误?
  • 首先突出显示所有这些mongoose.connect(uri, options)
  • 任何想法@titian-cernicova-dragomir
  • 没有足够的信息来表达想法,有些东西可能是空的,编译器告诉你在使用它之前检查它。但是如果没有重现错误的最小示例,或者没有更完整的定义,就很难说
  • 我已经用完整的代码更新了我的问题,如果你能看一下,我将不胜感激。 @titian-cernicova-dragomir

标签: node.js typescript mongoose


【解决方案1】:

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( … )

【讨论】:

  • 天才,ty :) 成功了const options: mongoose.ConnectionOptions
【解决方案2】:

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

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

但是,如果返回值确实恰好是null,这将在运行时崩溃。

【讨论】:

    猜你喜欢
    • 2021-07-11
    • 2021-02-14
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2021-05-04
    相关资源
    最近更新 更多