如何在Node.js应用程序中连接到mongoDs-Atlas?

时间:2019-05-22 10:09:50

标签: node.js mongodb mongodb-atlas

我正在尝试从node.js应用连接到我的mongoDb-Atlas

这是我的代码:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://username:<password>@cluster0-shard-00-00-afixn.mongodb.net:27017,cluster0-shard-00-01-afixn.mongodb.net:27017,cluster0-shard-00-02-afixn.mongodb.net:27017/Yarden?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true';
const client = new MongoClient(url);
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");
  client.close();
});

我得到的错误:

  

AssertionError [ERR_ASSERTION]:空== [AssertionError   [ERR_ASSERTION]:空==错误:密码包含非法的未转义字符   字符] {       在parseConnectionString(/Users/admin/Desktop/node/node_modules/mongodb/lib/url_parser.js:298:13)       在parseHandler(/Users/admin/Desktop/node/node_modules/mongodb/lib/url_parser.js:129:14)       在module.exports(/Users/admin/Desktop/node/node_modules/mongodb/lib/url_parser.js:25:12)       不推荐使用(internal / util.js:67:15)       在连接时(/ Users / admin / Desktop / node / node_modules / mongodb / lib / operati ...       在/Users/admin/Desktop/node/index.js:64:10       在err(/Users/admin/Desktop/node/node_modules/mongodb/lib/utils.js:411:14)       在executeCallback(/Users/admin/Desktop/node/node_modules/mongodb/lib/utils.js:401:25)       在executeOperation(/Users/admin/Desktop/node/node_modules/mongodb/lib/utils.js:418:7)       在MongoClient.connect(/Users/admin/Desktop/node/node_modules/mongodb/lib/mongo_client.js:175:10)       在对象。 (/用户/管理员/桌面/节点/index.js:63:8)       在Module._compile(内部/模块/cjs/loader.js:707:30)       在Object.Module._extensions..js(内部/模块/cjs/loader.js:718:10)       在Module.load(internal / modules / cjs / loader.js:605:32)       在tryModuleLoad(internal / modules / cjs / loader.js:544:12)

我尝试多次更改密码,它不包含任何特殊字符。

2 个答案:

答案 0 :(得分:1)

您的密码在URL上包含一些不允许使用的字符,请尝试使用uri_decode_auth: true

对其进行转义
mongoClient.connect("mongodb://username:p%40ssword@host:port/dbname", { 
    uri_decode_auth: true 
    }, function(err, db) {

    }
);

或者这样:

const dbUrl = `mongodb://username:${encodeURIComponent('@Password')}@localhost:27017/mydb`;

答案 1 :(得分:0)

将用户添加到mongodb并将username替换为您的用户名和密码,用用户密码!

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://your username:<your password>@cluster0-shard-00-00-afixn.mongodb.net:27017,cluster0-shard-00-01-afixn.mongodb.net:27017,cluster0-shard-00-02-afixn.mongodb.net:27017/Yarden?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true';
const client = new MongoClient(url);
client.connect(function(err) {
  assert.equal(null, err);
  console.log("Connected successfully to server");
  client.close();
});