【发布时间】:2020-10-25 10:48:29
【问题描述】:
我正在尝试使用 Typescript 加载 .env 环境变量。
这是我的 .env 和 app.ts 文件
//.env
DB_URL=mongodb://127.0.0.1:27017/test
// app.ts
import * as dotenv from 'dotenv';
import express from 'express';
import mongoose from 'mongoose';
dotenv.config();
mongoose.connect(process.env.DB_URL, config);
当我使用ts-node src/app.ts 命令运行app.ts 时,抛出此错误
Unable to compile TypeScript:
src/app.ts:50:18 - error TS2769: No overload matches this call.
Overload 1 of 3, '(uris: string, callback: (err: MongoError) => void): Promise<typeof import("mongoose")>', gave the following error.
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.
Overload 2 of 3, '(uris: string, options?: ConnectionOptions | undefined): Promise<typeof import("mongoose")>', gave the following error.
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.
50 mongoose.connect(process.env.DB_URL, config);
但是当我在下面添加 if 语句时,效果很好
//app.ts
import * as dotenv from 'dotenv';
import express from 'express';
import mongoose from 'mongoose';
dotenv.config();
//Add this code
if (!process.env.DB_URL) {
process.exit(1);
}
mongoose.connect(process.env.DB_URL, config);
Example app listening at http://localhost:3000
Mongoose default connection is open to mongodb://127.0.0.1:27017/test
我想知道为什么下面的代码没有抛出这个错误?
【问题讨论】:
-
你能把
console.log('DB_URL=' + process.env.DB_URL)和console.log('config=' + config)放在dotenv.config();之后并给出输出吗?
标签: mongodb typescript express