无效的连接字符串-process.env

时间:2019-12-05 01:47:48

标签: node.js mongodb mongoose

我要使用process.env

-这是db.js-

import * as dotenv from "dotenv";
import mongoose from "mongoose";

dotenv.config();

const { DB_URL } = process.env.PRODUCTION ? process.env : "localhost:27017/save-idiot"; 
const { DB_PROTOCOL } =process.env.PRODUCTION ? process.env : "mongodb"

mongoose.connect(`${DB_PROTOCOL}://${DB_URL}`, {
  useNewUrlParser: true,
  useFindAndModify: false,
  useUnifiedTopology: true
});

const db = mongoose.connection;

const handleOpen = () => console.log("✅ Connected to DB");

const handleError = error => console.log(`❌ Error on DB Connection:${error}`);

db.once("open", handleOpen);
db.on("error", handleError);

-package.json-

"scripts": {
    "dev:server": "nodemon --exec babel-node src/init.js -- delay 2",
    "dev:assets": "cd src && WEBPACK_ENV=development webpack -w",
    "lint": "eslint src/",
    "fix": "eslint --fix src/",
    "clean": "rm -rf build",
    "build:server": "babel src --out-dir build --ignore 'src/assets','src/static','src/webpack.config.js'",
    "build:assets": "cd src && WEBPACK_ENV=production webpack",
    "copy:static": "cp -R src/static src/views build/",
    "build": "npm run clean && npm run lint && npm run build:server && npm run build:assets && npm run copy:static",
    "start": "PRODUCTION=true forever start build/init.js"
  }
const { DB_URL } = process.env.PRODUCTION ? process.env : "localhost:27017/save-idiot"; 
const { DB_PROTOCOL } =process.env.PRODUCTION ? process.env : "mongodb"

如果我npm运行dev:server, 我想获取“ localhost:27017 / save-idiot”和“ mongodb”

如果我npm开始, 我想获取process.env

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以使用cross-env包,它用于设置环境变量。 安装后,您可以尝试如下操作: "start": "cross-env PRODUCTION=true forever start build/init.js"

答案 1 :(得分:0)

尝试使用

dotenv.config({ path: '.env' });

要配置许多环境,您可以使用envdist