node.js - 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( ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
解决方案
函数定义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( … )
推荐阅读
- delphi - 连接到 SSL 时出错 - Delphi 7 Indy 9
- nlp - 使用 pandas 数据框将自定义标签分配给 spacy
- stripe-payments - 条纹支付自定义样式
- react-native - 在 React Native 中浮动到 Int
- python - os.environ.get 返回无,但回显工作正常
- python-3.x - Scrapy yield does not display any results
- javascript - 如果同一组件有许多路由,history.push 和 Link 会更改 URL,并且不会重新呈现组件
- javascript - TypeError:回调不是函数,“node_modules\jsonwebtoken\sign.js:101:14)”
- c - 在while条件本身内部实现一个打破while的if条件
- c# - CNGKey.Create 不会持续存在