【发布时间】:2020-02-15 09:48:01
【问题描述】:
我使用typescript创建了一个node.js服务器,项目结构是这样的:
|--node_modules
|--server
.env
|-- build
|-- src
|-- database
|-- controllers
|-- models
|-- routes
|-- utils
|-- app.ts
|-- server.ts
app.ts:
import bodyParser from "body-parser";
import cors from "cors";
import { config } from "dotenv";
import express, { Express } from "express";
config({ path: __dirname + "../.env" });
import db from "./database/config";
db.once("open", () => logger.info("connected to the database"));
// checks if connection with the database is successful
db.on("error", console.error.bind(console, "MongoDB connection error:"));
const app: Express = express();
.
.
.
数据库/config.ts:
import mongoose from "mongoose";
import { logger } from "../utils/log";
const url = process.env.MONGODB_DEV_HOST;
mongoose
.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
})
.then(() => {
logger.info("Database starts successfully");
})
.catch((error) => {
logger.error("Error when starting database: \n", error);
});
const db = mongoose.connection;
export default db;
.env:
MONGODB_DEV_HOST=mongodb://localhost:27017/db
当我运行我的服务器时,由于 url 未定义,mongodbserver 出现错误。
我将.envfile 放在项目的根目录中。我是否遗漏了配置中的某些内容?
【问题讨论】:
标签: node.js mongodb typescript mongoose dotenv