mongodb Mongoose 错误:openUri()的uri参数必须是字符串,得到“未定义”

slhcrj9b  于 2022-12-18  发布在  Go
关注(0)|答案(2)|浏览(414)

我是新的在mongo和我尝试做一个连接,但我收到一个错误,我不知道如何解决,错误是如下:

MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string. did not connect
(node:21807) [MONGOOSE] DeprecationWarning: Mongoose: the `strictQuery` option will be switched back to `false` by default in Mongoose 7. Use `mongoose.set('strictQuery', false);` if you want to prepare for this change. Or use `mongoose.set('strictQuery', true);` to suppress this warning.
(Use `node --trace-deprecation ...` to show where the warning was created)

我的代码如下:
index.js

/* MONGOOSE SETUP */
    const PORT = process.env.PORT || 6001;
    mongoose
      .connect(process.env.MONGO_URL, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
      })
      .then(() => {
        app.listen(PORT, () => console.log(`Server Port: ${PORT}`));
      })
      .catch((error) => console.log(`${error} did not connect`));

.env文件

MONGO_URL= 'mongodb+srv://User:Password@cluster0.is8ykod.mongodb.net/?retryWrites=true&w=majority'
PORT = 3001


我认为MONGO_URL看起来不像字符串,但我不明白为什么,我已经尝试用途:

require('dotenv').config();

但在接收到该错误时:

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/gianlca/Desktop/progetto/server/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.

我不能重命名它像'.cjs'的原因,我在文件中的导入,他们开始不工作了

vuktfyat

vuktfyat1#

请确保已在URI上指定数据库名称。
URI应为'mongodb+srv://User:Password@cluster0.is8ykod.mongodb.net/yourDataBaseName?retryWrites=true&w=majority'

lrpiutwd

lrpiutwd2#

在package.json文件中:
如果有一行显示"type": "module",请将其更改为"type": "commonjs"
如果您没有以下行:添加"type:": "commonjs",如图所示

相关问题