我在启动 node.js 服务器时尝试连接到 MongoDB。我的服务器在 src/server.ts
, connectDB()
在 src/config/db.ts
和我的 .env
, 和 environment.d.ts
都在根目录下。但是,当尝试连接到数据库时,它仍然显示我的 MONGO_URI
,声明于 .env
, 类型为 string | undefined
.environment.d.ts
:
declare namespace NodeJS {
export interface ProcessEnv {
PORT?: string;
NODE_ENV: 'development' | 'production';
MONGO_URI: string;
}
}
src/server
:import dotenv from 'dotenv';
import express from 'express';
import connectDB from './config/db';
dotenv.config({ path: '../.env' });
connectDB();
const app = express();
.....
src/config/db.ts
:import mongoose from 'mongoose';
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
});
console.log(`MongoDB connected: ${conn.connection.host}`);
} catch (error) {
console.error(`ERROR: ${error.message}`);
process.exit(1);
}
};
export default connectDB;
完整的错误代码:TSError: ⨯ Unable to compile TypeScript:
src/config/db.ts:5:41 - error TS2769: No overload matches this call.
Overload 1 of 3, '(uri: string, callback: (err: CallbackError) => void): void', 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, '(uri: string, options?: ConnectOptions | 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'.
5 const conn = await mongoose.connect(process.env.MONGO_URI, {
我尝试声明 dotenv.config()
内db.ts
并在 server.ts
中声明时删除路径选项.将鼠标悬停在 VSCode 中的环境变量上显示 (property) NodeJS.ProcessEnv.MONGO_URI: string
.所以我真的认为这是正确的设置,但我一定错过了一些东西。
最佳答案
此错误可能是由于您的 tsconfig.json 文件规则造成的。很可能是由于 "strictNullChecks": true
你可能把这条规则放在 真 .
有两个简单的解决方案:
"strictNullChecks": false
. !
紧随其后 process.env.MONGO_URI
像这样:process.env.MONGO_URI!
.符号!
确保您的 typescript 转译器的值不会是 未定义 . 关于node.js - 无法识别环境变量的 TypeScript 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66038563/