繁体   English   中英

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

[英]MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined"

我是 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)

我的代码如下:

索引.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'一样重命名它因为我在文件中的导入它们也开始不起作用

确保您在 URI 上指定了数据库名称。

URI 应该是:

mongodb+srv://User:Password@cluster0.is8ykod.mongodb.net/yourDataBaseName?retryWrites=true&w=majority

在 package.json 文件中:

如果你有一行写着"type": "module"把它改成"type": "commonjs"

如果您没有该行:添加"type:": "commonjs" ,如图所示

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM