lpr*_*ard 7 environment-variables mongodb node.js typescript
我在启动 Node.js 服务器时尝试连接到 MongoDB。我的服务器位于src/server.ts、connectDB()和src/config/db.tsmy .env、 以及environment.d.ts根目录中。然而,当尝试连接到数据库时,它仍然说 my MONGO_URI,在 中声明.env,是 type string | undefined。
environment.d.ts:
declare namespace NodeJS {\n export interface ProcessEnv {\n PORT?: string;\n NODE_ENV: 'development' | 'production';\n MONGO_URI: string;\n }\n}\nRun Code Online (Sandbox Code Playgroud)\nsrc/server:
import dotenv from 'dotenv';\nimport express from 'express';\nimport connectDB from './config/db';\n\ndotenv.config({ path: '../.env' });\nconnectDB();\nconst app = express();\n\n.....\nRun Code Online (Sandbox Code Playgroud)\nsrc/config/db.ts:
import mongoose from 'mongoose';\n\nconst connectDB = async () => {\n try {\n const conn = await mongoose.connect(process.env.MONGO_URI, {\n useUnifiedTopology: true,\n useNewUrlParser: true,\n useCreateIndex: true,\n });\n\n console.log(`MongoDB connected: ${conn.connection.host}`);\n } catch (error) {\n console.error(`ERROR: ${error.message}`);\n process.exit(1);\n }\n};\n\nexport default connectDB;\nRun Code Online (Sandbox Code Playgroud)\n完整错误代码:
\nTSError: \xe2\xa8\xaf Unable to compile TypeScript:\nsrc/config/db.ts:5:41 - error TS2769: No overload matches this call.\n Overload 1 of 3, '(uri: string, callback: (err: CallbackError) => void): void', gave the following error.\n Argument of type 'string | undefined' is not assignable to parameter of type 'string'.\n Type 'undefined' is not assignable to type 'string'.\n Overload 2 of 3, '(uri: string, options?: ConnectOptions | undefined): Promise<typeof import("mongoose")>', gave the following error.\n Argument of type 'string | undefined' is not assignable to parameter of type 'string'.\n Type 'undefined' is not assignable to type 'string'.\n\n5 const conn = await mongoose.connect(process.env.MONGO_URI, {\nRun Code Online (Sandbox Code Playgroud)\n我尝试在 中声明它时声明dotenv.config()insidedb.ts并删除路径选项server.ts。将鼠标悬停在 VSCode 中的环境变量上会显示(property) NodeJS.ProcessEnv.MONGO_URI: string. 所以我真的认为这是正确的设置,但我一定错过了一些东西。
尝试将其添加到global.d.ts文件中,如下所示
declare global {
namespace NodeJS {
interface ProcessEnv {
PORT?: string;
NODE_ENV: 'development' | 'production';
MONGO_URI: string;
}
}
}
export {};
Run Code Online (Sandbox Code Playgroud)
此错误可能是由于您的 tsconfig.json 文件规则造成的。很可能是因为"strictNullChecks": true您可能已将此规则设置为true。有两个简单的解决方案:
"strictNullChecks": false。!立即添加: 。该符号确保您的打字稿转译器的值不会是undefined。process.env.MONGO_URIprocess.env.MONGO_URI!!| 归档时间: |
|
| 查看次数: |
9990 次 |
| 最近记录: |