密码的MongoDB URI连接环境变量不起作用。
const uri =
"mongodb+srv://ronnlidd:...@cluster0-qfs54.mongodb.net/test?retryWrites=true";
使用3个点作为密码字母可以正常工作,但是,如果我尝试这样做(安装dotenv并在单独的文件中创建变量):
const uri =
`mongodb+srv://ronnlidd:${process.env.MONGODB_PASSWORD}@cluster0-qfs54.mongodb.net/test?retryWrites=true`;
...我收到以下错误消息:
{ Error: querySrv ENOTFOUND _mongodb._tcp.cluster0.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:197:19)
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster0.mongodb.net' }
C:\CodingProjects\nodepractice\node_modules\mongodb\lib\mongo_client.js:233
throw new MongoError('MongoClient must be connected before calling MongoClient.prototype.db');
^
MongoError: MongoClient must be connected before calling MongoClient.prototype.db
at MongoClient.db (C:\CodingProjects\nodepractice\node_modules\mongodb\lib\mongo_client.js:233:11)
at client.connect.err (C:\CodingProjects\nodepractice\index.js:52:10)
at err (C:\CodingProjects\nodepractice\node_modules\mongodb\lib\utils.js:411:14)
at executeCallback (C:\CodingProjects\nodepractice\node_modules\mongodb\lib\utils.js:401:25)
at err (C:\CodingProjects\nodepractice\node_modules\mongodb\lib\operations\mongo_client_ops.js:285:21)
at parseFn (C:\CodingProjects\nodepractice\node_modules\mongodb\lib\operations\mongo_client_ops.js:197:21)
at QueryReqWrap.dns.resolveSrv [as callback] (C:\CodingProjects\nodepractice\node_modules\mongodb-core\lib\uri_parser.js:56:21)
at QueryReqWrap.onresolve [as oncomplete] (dns.js:197:10)
[nodemon] app crashed - waiting for file changes before starting...
代码的上下文是这样的: 上面定义的URI:
const MongoClient = mongodb.MongoClient;
在URI之下被定义:
const client = new MongoClient(uri, { useNewUrlParser: true });
谢谢。