mongoose 连接错误:openUri()的uri参数必须是字符串,获得“object”

bq9c1y66  于 2023-03-08  发布在  Go
关注(0)|答案(2)|浏览(109)

我试图连接我的MERN堆栈应用程序到MongoDB通过使用mongoose,但我得到这个错误,即使我使用dotenv文件或直接.我已经搜索了许多解决方案,但没有为我工作,请帮助,如果你知道是什么问题.
是不是因为dotenv文件不在根文件夹中?我不知道根文件夹应该是什么,如果你知道请告诉我。
服务器文件夹中的index.js文件:

import express from 'express';
        import bodyparser from 'body-parser';
        import mongoose from 'mongoose';
        import cors from 'cors';
        import dotenv from 'dotenv';
        import postRoutes from './routes/posts.js'
        
        const app = express();
        dotenv.config();
        
        app.use('./posts',postRoutes);
        
        app.use(bodyparser.json({limit: '30mb',extended: true}));
        app.use(bodyparser.urlencoded({limit: '30mb',extended: true}));
        app.use(cors());
        
        const PORT = process.env.PORT || 5000;
        
        mongoose.connect((process.env.MONGO_URI, {useNewUrlParser:true, useUnifiedTopology: true}))
        .then(()=> app.listen(PORT, ()=> console.log( `server running: ${PORT}`)))
        .catch((error) => console.log(error.message));

服务器文件夹的此package.json文件:

{
                  "name": "server",
                  "version": "1.0.0",
                  "description": "",
                  "main": "index.js",
                  "type": "module",
                  "scripts": {
                    "start": "nodemon index.js"
                  },
                  "keywords": [],
                  "author": "",
                  "license": "ISC",
                  "dependencies": {
                    "body-parser": "^1.20.0",
                    "cors": "^2.8.5",
                    "dotenv": "^16.0.0",
                    "dotenv-config": "^0.1.1",
                    "express": "^4.17.3",
                    "mongoose": "^6.2.10",
                    "nodemon": "^2.0.15"
                  }
                }

启动服务器时出现错误:

[nodemon] clean exit - waiting for changes before restart
            [nodemon] restarting due to changes...
            [nodemon] starting `node index.js`
            The `uri` parameter to `openUri()` must be a string, got "object". 
            Make sure the first parameter to `mongoose.connect()` or ` 
            mongoose.createConnection()` is a string.

我已经在网上看到一些解决方案,但没有工作。服务器仍然没有运行,我不能在其他模块的工作,请帮助。
当我不使用env文件,直接把mongo字符串,仍然得到同样的错误,而且我没有取代mydatabasename在mongo网址。
启动服务器时出现错误:

[nodemon] clean exit - waiting for changes before restart
            [nodemon] restarting due to changes...
            [nodemon] starting `node index.js`
            The `uri` parameter to `openUri()` must be a string, got "object". 
            Make sure the first parameter to `mongoose.connect()` or ` 
            mongoose.createConnection()` is a string.

我现在该写什么呢?这是我的问题。我想我已经把所有重要的细节都写出来了。我想我没有别的选择了,只能再复制粘贴一遍。

cuxqih21

cuxqih211#

我理解我以前遇到的挫折。不要给予!看起来你大部分都做对了,但是我在阅读const PORT = process.env.PORT || 5000;这行下面的内容时遇到了麻烦
我会这样处理:

const PORT = process.env.PORT || 5000;

// your code above ^^

const connectionString = ``;

mongoose.connect(connectionString, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
  // we're connected!
});

/**
 * Server Activation
 */
app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}`);
});

还有一些提示:

  • 把你的.env文件和package.json文件放在同一层,通常是项目的“根”。
  • 调试问题时最好忽略环境变量,直接放入内容,这样可以排除外部因素
rseugnpd

rseugnpd2#

谢谢你@特雷弗Njeru!!😁
我有同样的错误,我解决了。这是由于.env文件的位置。我移动了它,所以它沿着根目录休息,这是一个有package.json文件。(我也没有应用其他人提供的解决方案:我没有指定“路径”:需要('dotenv').config(路径:“./.env”)。没有。我只是按要求离开('dotenv').config()。
只要确保.env与服务器端的package.json一起存在,它就对我起作用了。
再次感谢您!

相关问题