我有一个数据库包装类,它建立与某些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身份运行,而这些警告会导致垃圾邮件垃圾邮件。
我在mongodb
版本中使用3.1.0-beta4
驱动程序,并在@types/mongodb
中使用相应的3.0.18
包。它们都是使用npm install
的最新版本。
使用旧版本的mongodb驱动程序:
"mongodb": "~3.0.8",
"@types/mongodb": "~3.0.18"
检查你的mongo版本
mongo --version
如果您使用的是版本> = 3.1.0,请将mongo连接文件更改为 - >
MongoClient.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true })
或者您的mongoose连接文件 - >
mongoose.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true });
理想情况下,它是版本4的功能,但v3.1.0及更高版本也支持它。查看MongoDB Github了解详情。
expressJS,api调用case和json发送的完整示例如下:
...
app.get('/api/myApi', (req, res) => {
MongoClient.connect('mongodb://user:[email protected]: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()
},
)
})
}
这是我的方式,在我几天前更新npm之前,提示没有显示在我的控制台上。
.connect有3个参数,URI,选项和错误。
mongoose.connect(
keys.getDbConnectionString(),
{ useNewUrlParser: true },
err => {
if (err) throw err;
console.log(`Successfully connected to database.`);
}
);
**We were using**
mongoose.connect("mongodb://localhost/mean-course").then(
(res) => {
console.log("Connected to Database Successfully.")
}
).catch(() => {
console.log("Conntection to database failed.");
});
*-----> This gives url parser error*
**Correct Syntax is**:
mongoose.connect("mongodb://localhost:27017/mean-course" , { useNewUrlParser: true }).then(
(res) => {
console.log("Connected to Database Successfully.")
}
).catch(() => {
console.log("Conntection to database failed.");
});
你只需要添加
{useNewUrlParser:true}
在mongoose.connect方法中
我使用mlab.com作为mongo数据库。我将连接字符串分隔到一个名为config的不同文件夹,并在keys.js内部保留了连接字符串
module.exports = {
mongoURI: "mongodb://username:[email protected]:47267/projectname"
};
和服务器代码是
const express = require("express");
const mongoose = require("mongoose");
const app = express();
//DB config
const db = require("./config/keys").mongoURI;
//connect to mongo DB
mongoose
.connect(
db,
{ useNewUrlParser: true } //need this for api support
)
.then(() => console.log("mongoDB connected"))
.catch(err => console.log(err));
app.get("/", (req, res) => res.send("hello!!"));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`)); //tilda not inverted comma
您需要在连接字符串之后写{useNewUrlParser:true},如上所述。
简单地说你需要做:
mongoose.connect(connectionString,{ useNewUrlParser: true }
//or
MongoClient.connect(connectionString,{ useNewUrlParser: true }
这些行也为所有其他弃用警告提供了技巧:
const db = await mongoose.createConnection(url, { useNewUrlParser: true });
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
如果username
或password
有@
字符。然后像这样使用
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));
正如所指出的那样,3.1.0-beta4
释放的驱动程序在事物看起来早一点“释放到野外”。该版本是正在进行的工作的一部分,以支持MongoDB 4.0即将发布的版本中的新功能,并进行一些其他API更改。
触发当前警告的一个这样的更改是useNewUrlParser
选项,因为关于如何传递连接URI实际工作的一些变化。稍后会详细介绍。
在事情“安定下来”之前,至少对advisable to "pin"版本的次要版本可能是3.0.x
:
"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
和后续版本,理想情况下,通过启用useNewUrlParser
中的MongoClient.connect()
选项,确保提供对新解析器有效的连接字符串。
如果您实际上不需要访问与MongoDB 4.0版本预览相关的功能,那么请将版本固定到3.0.x
系列,如前所述。这将按照文档记录并“固定”这确保3.1.x
版本不会在预期的依赖项上“更新”,直到您真正想要安装稳定版本。
下面突出显示的mongoose连接代码解决了猫鼬驱动程序的警告
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true });
没有什么可以改变,只通过连接功能{useNewUrlParser: true }
这将工作
MongoClient.connect(url,{ useNewUrlParser: true },function(err,db){
if(err){
console.log(err);
}
else {
console.log('connected to '+ url);
db.close();
}
})
需要在mongoose.connect()方法中添加{ useNewUrlParser: true }
。
mongoose.connect('mongodb://localhost:27017/Notification',{ useNewUrlParser: true });
连接字符串格式必须是mongodb:// user:password @ host:port / db
例如:
MongoClient.connect('mongodb://user:[email protected]:27017/yourDB', { useNewUrlParser: true } )
我认为你不需要添加{ useNewUrlParser: true }
。
如果你想使用新的url解析器,这取决于你。最终,当mongo切换到新的url解析器时,警告将消失。
编辑:如此处指定https://docs.mongodb.com/master/reference/connection-string/您不需要设置端口号。
只需添加{ useNewUrlParser: true }
就足够了。
通过提供端口号并使用此解析器{useNewUrlParser:true}可以解决该问题。解决方案可以是:
mongoose.connect("mongodb://localhost:27017/cat_app", { useNewUrlParser: true });
它解决了我的问题。
不正确的ES8 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
}