ChatGPT解决这个技术问题 Extra ChatGPT

通过将 useNewUrlParser 设置为 true 来避免“不推荐使用当前 URL 字符串解析器”警告

我有一个数据库包装类,它建立到某个 MongoDB 实例的连接:

async connect(connectionString: string): Promise<void> {
        this.client = await MongoClient.connect(connectionString)
        this.db = this.client.db()
}

这给了我一个警告:

(node:4833) DeprecationWarning:当前的 URL 字符串解析器已被弃用,并将在未来的版本中删除。要使用新的解析器,请将选项 { useNewUrlParser: true } 传递给 MongoClient.connect。

connect() 方法接受 MongoClientOptions 实例作为第二个参数。但它没有名为 useNewUrlParser 的属性。我还尝试在连接字符串中设置这些属性,如下所示:mongodb://127.0.0.1/my-db?useNewUrlParser=true 但它对这些警告没有影响。

那么如何设置 useNewUrlParser 来删除这些警告呢?这对我很重要,因为脚本应该作为 cron 运行,并且这些警告会导致垃圾邮件垃圾邮件。

我正在使用版本 3.1.0-beta4 中的 mongodb 驱动程序和 3.0.18 中的相应 @types/mongodb 包。它们都是使用 npm install 的最新版本。

解决方法

使用旧版本的 mongodb 驱动程序:

"mongodb": "~3.0.8",
"@types/mongodb": "~3.0.18"
这来自于周末在 npm 上发布的 beta 版本。在 API 真正完成之前不要担心。您安装了稳定版本是正确的。
以上 3.0.0 的 mongodb 添加简单 mongoose.connect("mongodb://localhost:portnumber/YourDB", { useNewUrlParser: true })

P
Peter Mortensen

检查您的 mongo 版本:

mongo --version

如果您使用的版本 >= 3.1.0,请将您的 mongo 连接文件更改为 ->

MongoClient.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true })

或者你的猫鼬连接文件到->

mongoose.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true });

理想情况下,它是第 4 版功能,但 v3.1.0 及更高版本也支持它。查看MongoDB GitHub了解详情。


@AbhishekSinha 为什么使用 mongo >= 4.0.0?我正在使用 3.6.5,烦人的消息也消失了。
是的,解决了这个问题。基本上,它是 v4 功能,但 v3.1.0 及更高版本也支持新功能。
这是最好的,只是想补充一下,如果你有一个回调,尤其是错误,只需使用这个: mongoose.connect(dbUrl, { useNewUrlParser: true }, function(err) { console.log("mongoDB connected",呃); })
B
Ben Froelich

如前所述,从外观上看,驱动程序的 3.1.0-beta4 版本“发布到野外”有点早。该版本是正在进行的工作的一部分,以支持即将发布的 MongoDB 4.0 版本中的新功能并进行一些其他 API 更改。

触发当前警告的此类更改之一是 useNewUrlParser 选项,这是由于有关传递连接 URI 实际工作方式的一些更改。稍后再谈。

在事情“稳定下来”之前,至少对于 3.0.x 版本的次要版本可能是 advisable to "pin"

  "dependencies": {
    "mongodb": "~3.0.8"
  }

这应该会停止在节点模块的“新”安装上安装 3.1.x 分支。如果您已经安装了“最新”版本,即“beta”版本,那么您应该清理您的软件包(和 package-lock.json )并确保将其升级为 3.0.x 系列版本。

至于实际使用“新”连接 URI 选项,主要限制是在连接字符串中实际包含 port

const { MongoClient } = require("mongodb");
const uri = 'mongodb://localhost:27017';  // mongodb://localhost - will fail

(async function() {
  try {

    const client = await MongoClient.connect(uri,{ useNewUrlParser: true });
    // ... anything

    client.close();
  } catch(e) {
    console.error(e)
  }

})()

这是新代码中更“严格”的规则。要点是当前代码本质上是“node-native-driver”(npm mongodb)存储库代码的一部分,而“新代码”实际上是从“支撑”“公共”的 mongodb-core 库导入的" 节点驱动程序。

添加“选项”的目的是通过将选项添加到新代码来“缓解”转换,以便在代码中使用较新的解析器(实际上基于 url )添加选项并清除弃用警告,并且因此验证您传入的连接字符串实际上是否符合新解析器的预期。

在未来的版本中,“旧”解析器将被删除,然后新的解析器将只是使用的,即使没有该选项。但到那时,预计所有现有代码都有足够的机会根据新解析器的预期测试其现有连接字符串。

因此,如果您想在新的驱动程序功能发布时开始使用它们,请使用可用的 beta 和后续版本,并在理想情况下通过启用MongoClient.connect()

如果您实际上不需要访问与 MongoDB 4.0 版本预览相关的功能,请将该版本固定到 3.0.x 系列,如前所述。这将按照记录和“固定”工作,这确保 3.1.x 版本不会“更新”超过预期的依赖关系,直到您真正想要安装稳定版本。


当您说“被释放到野外”时,您是否有更多关于您的意思的信息? 3.1.0-beta4是怎么逃出动物园的?你能引用任何关于那个的参考吗?
@Wyck“参考”当然是在提出问题时,执行 npm install mongodb 导致安装 "beta" (在问题中显示的版本字符串中明确标记)自它在 npm 存储库中被标记为 stable,而它不应该被标记为。这在当时确实是一个错误,如果任何在版本字符串中显示 alphabeta 的代码版本同样被标记为稳定,则应始终予以考虑。自然地,时间已经过去了,这是现在稳定版本中的一个特性,直到(如前所述)它最终会消失。
P
Peter Mortensen

下面突出显示的 mongoose 连接代码解决了 mongoose 驱动程序的警告:

mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });

不为我工作。仍然得到:(节点:35556)DeprecationWarning:当前的 URL 字符串解析器已被弃用,并将在未来的版本中删除。要使用新的解析器,请将选项 { useNewUrlParser: true } 传递给 MongoClient.connect。
如果仍然无法正常工作,则必须在提供数据库路径的任何地方保存 server.js 或 app.js
p
peinearydevelopment

没有什么可以改变的。仅传入连接函数 {useNewUrlParser: true }

这将起作用:

    MongoClient.connect(url, {useNewUrlParser:true,useUnifiedTopology: true }, function(err, db) {
        if(err) {
            console.log(err);
        }
        else {
            console.log('connected to ' + url);
            db.close();
        }
    })

正是我需要的,但警告信息仍然存在:-S
对我有用,不再有警告。
P
Peter Mortensen

您只需要在连接到数据库之前设置以下内容,如下所示:

const mongoose = require('mongoose');

mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);

mongoose.connect('mongodb://localhost/testaroo');

还,

Replace update() with updateOne(), updateMany(), or replaceOne()
Replace remove() with deleteOne() or deleteMany().
Replace count() with countDocuments(), unless you want to count how many documents are in the whole collection (no filter).
In the latter case, use estimatedDocumentCount().

应该是最佳答案。对我来说,所有其他答案都失败了。
如果对您有用,请将答案标记为 correct。它也对我有用!
t
turivishal

您需要在 mongoose.connect() 方法中添加 { useNewUrlParser: true }

mongoose.connect('mongodb://localhost:27017/Notification',{ useNewUrlParser: true });

这个答案与几个月前发布的其他答案相同
这与以前的答案有何不同?
@PeterMortensen 请检查最先发布答案的日期
P
Peter Mortensen

连接字符串格式必须为 mongodb://user:password@host:port/db

例如:

MongoClient.connect('mongodb://user:password@127.0.0.1:27017/yourDB', { useNewUrlParser: true } )

没有。MongoClient.connect('mongodb://127.0.0.1:27017/yourDB', { useNewUrlParser: true } ) 也可以。
这与以前的答案有何不同?
P
Peter Mortensen

以下对我有用

const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost/playground", { useNewUrlParser: true,useUnifiedTopology: true })
.then(res => console.log('Connected to db'));

mongoose 版本是 5.8.10


这个也对我有用。我正在使用-- body-parser": "^1.19.0", "express": "^4.17.1", "mongoose": "^5.9.14"
P
Peter Mortensen

该问题可以通过提供端口号并使用此解析器来解决:{useNewUrlParser: true}

解决方案可以是:

mongoose.connect("mongodb://localhost:27017/cat_app", { useNewUrlParser: true });

它解决了我的问题。


控制台本身提供了在 connect 中添加 useNewUrlParser property 的解决方案,但您的解决方案有所帮助。如此赞成!
P
Peter Mortensen

我认为您不需要添加 { useNewUrlParser: true }

如果您想使用新的 URL 解析器,这取决于您。最终,当 MongoDB 切换到新的 URL 解析器时,警告将消失。

Connection String URI Format 中所述,您无需设置端口号。

只需添加 { useNewUrlParser: true } 即可。


我添加了端口号,但仍然收到错误消息。我发现错误消息非常令人困惑和误导:为什么我会收到一条消息告诉我使用新格式,而实际上我使用的是旧格式并且它工作得很好......!!??
好问题!请注意,这是一个警告。不是错误。只有加入 useNewUrlParser: true,警告才会消失。但这有点愚蠢,因为一旦 mongo 切换到新的 url 解析器,这个额外的参数就会过时。
你怎么知道端口号是新的 url 解析器所期望的?我找不到任何实际描述新 url 解析器是什么的东西
@Brad,确实。我假设您需要添加端口号,但 Mongo 规范仍然提到端口号是可选的。我相应地更新了我的答案。
P
Peter Mortensen

针对 ECMAScript 8 更新 / 等待

不正确的 ECMAScript 8 demo code MongoDB inc provides 也会产生此警告。

MongoDB 提供以下建议,这是不正确的

要使用新的解析器,请将选项 { useNewUrlParser: true } 传递给 MongoClient.connect。

这样做会导致以下错误:

TypeError:executeOperation 的最后一个参数必须是回调

而是必须将选项提供给 new MongoClient

请看下面的代码:

const DATABASE_NAME = 'mydatabase',
    URL = `mongodb://localhost:27017/${DATABASE_NAME}`

module.exports = async function() {
    const client = new MongoClient(URL, {useNewUrlParser: true})
    var db = null
    try {
        // Note this breaks.
        // await client.connect({useNewUrlParser: true})
        await client.connect()
        db = client.db(DATABASE_NAME)
    } catch (err) {
        console.log(err.stack)
    }

    return db
}

P
Peter Mortensen

Express.js、API 调用案例和发送 JSON 内容的完整示例如下:

...
app.get('/api/myApi', (req, res) => {
  MongoClient.connect('mongodb://user:password@domain.com:port/dbname',
    { useNewUrlParser: true }, (err, db) => {

      if (err) throw err
      const dbo = db.db('dbname')
      dbo.collection('myCollection')
        .find({}, { _id: 0 })
        .sort({ _id: -1 })
        .toArray(
          (errFind, result) => {
            if (errFind) throw errFind
            const resultJson = JSON.stringify(result)
            console.log('find:', resultJson)
            res.send(resultJson)
            db.close()
          },
        )
    })
}

c
coderLogs

以下适用于 mongoose 版本 5.9.16

const mongoose = require('mongoose');

mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);

mongoose.connect('mongodb://localhost:27017/dbName')
    .then(() => console.log('Connect to MongoDB..'))
    .catch(err => console.error('Could not connect to MongoDB..', err))

P
Peter Mortensen

这就是我的方式。直到几天前我更新了 npm,提示才显示在我的控制台上。

.connect 有三个参数,URI、options 和 err。

mongoose.connect(
    keys.getDbConnectionString(),
    { useNewUrlParser: true },
    err => {
        if (err) 
            throw err;
        console.log(`Successfully connected to database.`);
    }
);

C
Community

我们正在使用:

mongoose.connect("mongodb://localhost/mean-course").then(
  (res) => {
   console.log("Connected to Database Successfully.")
  }
).catch(() => {
  console.log("Connection to database failed.");
});

→ 这会导致 URL 解析器错误

正确的语法是:

mongoose.connect("mongodb://localhost:27017/mean-course" , { useNewUrlParser: true }).then(
  (res) => {
   console.log("Connected to Database Successfully.")
  }
).catch(() => {
  console.log("Connection to database failed.");
});

添加一些描述
f
fedu

这些行也解决了所有其他弃用警告:

const db = await mongoose.createConnection(url, { useNewUrlParser: true });
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);

P
Peter Mortensen

我正在为我的项目使用猫鼬版本 5.x。需要 mongoose 包后,全局设置值如下。

const mongoose = require('mongoose');

// Set the global useNewUrlParser option to turn on useNewUrlParser for every connection by default.
mongoose.set('useNewUrlParser', true);

C
Chamon Roy

这对我很有效:

mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology", true);
mongoose
  .connect(db) //Connection string defined in another file
  .then(() => console.log("Mongo Connected..."))
  .catch(() => console.log(err));

b
bhargav3vedi
const mongoose = require('mongoose');

mongoose
  .connect(connection_string, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then((con) => {
    console.log("connected to db");
  });

尝试使用这个


t
turivishal

我使用 mlab.com 作为 MongoDB 数据库。我将连接字符串分隔到另一个名为 config 的文件夹中,并在文件 keys.js 中保留了连接字符串:

module.exports = { mongoURI: "mongodb://username:password@ds147267.mlab.com:47267/projectname" };

服务器代码是

常量表达 = 要求(“表达”);常量猫鼬 = 要求(“猫鼬”);常量应用程序 = 快递(); // 数据库配置 const db = require("./config/keys").mongoURI; // 连接到 MongoDB mongoose .connect( db, { useNewUrlParser: true } // 需要这个来支持 API ) .then(() => console.log("MongoDB connected")) .catch(err => console.log (呃)); app.get("/", (req, res) => res.send("hello!!"));常量端口 = process.env.PORT || 5000; app.listen(port, () => console.log(`Server running on port ${port}`)); // 波浪号,不是倒逗号

您需要在连接字符串之后写 { useNewUrlParser: true },就像我上面所做的那样。

简而言之,您需要执行以下操作:

mongoose.connect(connectionString,{ useNewUrlParser: true } // 或者 MongoClient.connect(connectionString,{ useNewUrlParser: true }


P
Peter Mortensen

如果 usernamepassword 具有 @ 字符,则像这样使用它:

mongoose
    .connect(
        'DB_url',
        { user: '@dmin', pass: 'p@ssword', useNewUrlParser: true }
    )
    .then(() => console.log('Connected to MongoDB'))
    .catch(err => console.log('Could not connect to MongoDB', err));

J
Jamal Kaksouri

(node:16596) DeprecationWarning:当前的 URL 字符串解析器已被弃用,并将在未来的版本中删除。要使用新的解析器,请将选项 { useNewUrlParser: true } 传递给 MongoClient.connect。 (使用 node --trace-deprecation ... 显示警告的创建位置)(node:16596)[MONGODB DRIVER] 警告:当前的服务器发现和监控引擎已被弃用,并将在未来的版本中删除。要使用新的服务器发现和监控引擎,请将选项 { useUnifiedTopology: true } 传递给 MongoClient 构造函数。

用法:

async connect(connectionString: string): Promise<void> {
        this.client = await MongoClient.connect(connectionString, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
  })
        this.db = this.client.db()
}

关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅