`openUri()` 的 `uri` 参数必须是一个字符串,得到“未定义”

Ali*_*Ali 11 javascript mongoose node.js

我对此进行了很多搜索,但没有一个可以帮助我。

当我运行我的项目时,我收到此错误:

/home/ali/Desktop/personalitytest-backend/node_modules/mongoose/lib/connection.js:428 throw new MongooseError('The uriparameter to openUri()must be a ' + ^ MongooseError: The uriparameter to openUri()must be a string, got "undefined" . 确保第一个参数 to mongoose.connect()mongoose.createConnection()是一个字符串。

我的 index.js 文件:

const express = require('express'),
  app = express(),
  mongoose = require('mongoose'),
  rateLimit = new require('express-rate-limit')({
    windowMs: 1000 * 60 * 10,
    max: 500,
    handler: (req, res) => {
      res.json({
        data: 'Your request was too much, please try again in 10 minutes later.',
        status: 'error'
      })
    }
  });
const Application = new class {
  constructor() {
    this.setConfig();
    this.setupDB();
    this.setRouters();
    this.setupExpress();
  }
  setConfig() {
    require('dotenv').config();
    app.use(require('helmet')());
    app.use(express.json());
  }
  setupDB() {
    mongoose.Promise = global.Promise;
    mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true, useCreateIndex: true });
  }
  setRouters() {
    app.use('/', require('./routes'));
  }
  setupExpress() {
    app.listen(process.env.PORT, () => console.log(`Listening on port ${process.env.PORT}.`));
    // app.listen(process.env.PORT, process.env.IP, () => console.log(`Listening on port ${process.env.PORT}.`));
  }
}
Run Code Online (Sandbox Code Playgroud)

我的 .env 文件:

PORT=3000
DATABASE_URL=mongodb://localhost:27017/PersonalityTest
JWT_SECRETKEY=asfdawetq312etr%!@$qe
Run Code Online (Sandbox Code Playgroud)

如果我只是在 mongoose.connect 方法中写数据库 url,不会有错误。

例如,这没有错误:

mongoose.connect("mongodb://localhost:27017/PersonalityTest", { useNewUrlParser: true, useCreateIndex: true });
Run Code Online (Sandbox Code Playgroud)

Mis*_*orp 9

要读取.env-file,您需要安装一些可以读取该文件的东西,例如dotenv

npm install dotenv --save
Run Code Online (Sandbox Code Playgroud)

然后你需要在你的代码中使用这个包

require('dotenv').config();
Run Code Online (Sandbox Code Playgroud)

根据dotenv文档,你应该这样做

尽早在您的应用程序中,要求并配置 dotenv。

接下来您可能需要在您的DATABASE_URL值周围添加双引号

DATABASE_URL="mongodb://localhost:27017/PersonalityTest"
Run Code Online (Sandbox Code Playgroud)

  • 我做了所有的项目,但没有得到结果,仍然有错误。 (2认同)

oxk*_*k4r 7

您是否检查过您的 .env 变量是否可以从该 index.js 文件中读取?

例如,查看将其中一些记录到控制台时得到的结果:

console.log(process.env.DATABASE_URL);
Run Code Online (Sandbox Code Playgroud)

如果您得到“未定义”,那么您可以尝试像这样指定 .env 文件的绝对路径:

const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, './.env') });
Run Code Online (Sandbox Code Playgroud)

我最近在解决这个问题,在我的情况下解决了这个问题。问候。


小智 5

这对我来说工作

const dotenv = require('dotenv')
dotenv.config({path:__dirname+'/.env'});
Run Code Online (Sandbox Code Playgroud)