【问题标题】:Cannot connect to MongoDB via env variable无法通过环境变量连接到 MongoDB
【发布时间】:2020-04-08 02:10:57
【问题描述】:

我试图隐藏我的连接字符串,所以我在我的项目中安装了 env2。然后我制作了一个 config.env 文件来保存我的连接字符串,如下所示:

export DB_URL='mongodb://user:userPassword@ds241968.mlab.com:41968/heroku_hc9xjmcl'

但是,当我将该变量用作连接字符串时,我无法连接到 Mlab,我收到以下错误:

UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [ds241968.mlab.com:41968] on first connect [MongoError: Authentication failed.]

但是,当我尝试仅连接字符串而不使用 env2 时,我可以完美连接,那么为什么当我使用 env 变量时验证失败以及如何正确连接呢?这是我的 server.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 || 3009;
const itemRoutes = express.Router();
let Comment = require('./comment.model');
const env = require('env2')('../config.env');
console.log(process.env.DB_URL)
app.use(cors());
app.use(bodyParser.json());
const { DB_URL } = process.env;


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);
})

【问题讨论】:

  • 当您尝试console.log(DB_URL); 时会得到什么?
  • 尝试删除连接字符串周围的引号
  • @MEDZ 我得到的连接 url 与变量中的完全一样
  • @Intellidroid 如果我删除字符串,我会收到此错误:cdconnection is not defined
  • 您实际上是否也在 Heroku 上托管您的应用程序?如果你是的话,也许可以在那里使用他们的环境变量?

标签: node.js mongodb heroku mongoose mlab


【解决方案1】:

看起来您正在使用 Node 和 Heroku。在这种情况下,

  1. 您应该设置 Heroku Config Vars(您可以通过 CLI 或 Heroku Dashboard 进行此操作)
  2. 以您现在所指的相同方式引用节点应用程序中的配置变量。
  3. 删除“env2”相关代码,因为您不需要它来实现此目的

例如,如果您创建名为“MONGO_URI”的 Heroku 配置变量,请在节点应用程序中将其称为 process.env.MONGO_URI。

详情请见:https://devcenter.heroku.com/articles/config-vars#managing-config-vars

【讨论】:

    猜你喜欢
    • 2019-09-16
    • 1970-01-01
    • 2022-01-21
    • 2018-04-02
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多