【问题标题】:connection to MongoDB via env variable returns DB_URL is not defined通过 env 变量连接到 MongoDB 返回 DB_URL 未定义
【发布时间】:2020-04-07 17:05:45
【问题描述】:

我正在尝试使用 config.env 文件中的 env 变量连接到我的 MongoDB 数据库,这样我的连接字符串就不会对所有人可见,但我不断收到我的 DB_URL is not defined 的错误,为什么?我该怎么做?我安装了env2,然后我创建了我的confing.env,它看起来像这样:

export DB_URL='mongodb://admin:username@password/heroku_url';

然后我在我的服务器 js 中需要它,如下所示:

// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3001;
const itemRoutes = express.Router();
let Comment = require('./comment.model');
require('env2')('../config.env')

app.use(cors());
app.use(bodyParser.json());


mongoose.connect(DB_URL, { useNewUrlParser: true } )

const connection = mongoose.connection;

connection.once('open', function() {
  console.log('Connection to MongoDB established succesfully!');
});

// Serve static assets
if(process.env.NODE_ENV === 'production') {
  app.use(express.static('build'));
}

itemRoutes.route('/').get( async (req, res) => {
  let collection = connection.collection("posts");
  let response = await collection.find({})
  .toArray();
  res.send(response);
});

itemRoutes.route('/comments').get( async (req, res) => {
  let collection = connection.collection("comments");
  let response = await collection.find({})
  .toArray();
  res.send(response);
});

itemRoutes.route('/userComments')
.post((req, res) => {
   res.setHeader('Content-Type', 'application/json');
   let comment = new Comment(req.body);
   comment.save()
   .then(comment => {
     res.status(200).json({comment})
   })
   .catch(err => {
     res.status(400).send('failed')
   })
});


app.use('/', itemRoutes);
app.use('/userComments', itemRoutes);


app.listen(PORT, function() {
  console.log('Server is running on' + ' ' + PORT);
})

【问题讨论】:

    标签: node.js mongodb environment-variables


    【解决方案1】:

    您应该使用 process.env.DB_URL 而不是 DB_URL

    像这样:mongoose.connect(process.env.DB_URL, { useNewUrlParser: true } )

    查看文档:https://www.npmjs.com/package/env2#use-in-your-code

    【讨论】:

      猜你喜欢
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-12
      • 2020-07-11
      • 2018-06-29
      • 2020-04-08
      • 2020-04-23
      • 2020-06-29
      相关资源
      最近更新 更多