Mongoose with ReplicaSet on Atlas

I have a replica set on Atlas MongoDB, and this is my mongo shell connection string that connects perfectly:

$ mongo "mongodb://MY_SERVER-shard-00-00-clv3h.mongodb.net:27017,MY_SERVER-shard-00-01-clv3h.mongodb.net:27017,MY_SERVER-shard-00-02-clv3h.mongodb.net:27017/MY_DATABASE?replicaSet=MY_REPLICASET-NAME-shard-0" --ssl --username MY_USERNAME --password MY_PASSWORD --authenticationDatabase MY_ADMIN_DATABASE 

How can I convert it for use in mongoose? How can I create my uri and options variable?

I tried the following without success:

  // connection string using mongoose: var uri = 'mongodb://MY_USER: MY_PASSWORD@ ' + 'MY_SERVER-shard-00-00-clv3h.mongodb.net:27017,' + 'MY_SERVER-shard-00-01-clv3h.mongodb.net:27017,' + 'MY_SERVER-shard-00-02-clv3h.mongodb.net:27017/MY_DATABASE'; var options = { replset: { ssl: true, authSource: 'MY_ADMIN_DATABASE', rs_name: 'MY_REPLICASET_NAME-shard-0' } }; mongoose.connect(uri, options); var db = mongoose.connection; 

I tried to enable user: and pass: by parameters, removing MY_USER: MY_PASSWORD @ from uri, change rs_name to replicaSet, every failed attempt. The mongoose doesn't seem to be considering an authSource option.

Using mongojs, it works fine with the following code:

  // connection string using mongojs: var uri = 'mongodb://MY_USER: MY_PASSWORD@ ' + 'MY_SERVER-shard-00-00-clv3h.mongodb.net:27017,' + 'MY_SERVER-shard-00-01-clv3h.mongodb.net:27017,' + 'MY_SERVER-shard-00-02-clv3h.mongodb.net:27017/MY_DATABASE'; var options = { ssl: true, authSource: 'MY_ADMIN_DATABASE', replicaSet: 'MY_REPLICASET_NAME-shard-0' }; var db = mongojs(uri,'', options); 

But I need to use mongoose because ODM is in my project.

How can I create my uri and options variable using mongoose?

+5
source share
2 answers

I solved this problem by setting the "options" value directly to the "uri" line according to the documentation ( http://mongoosejs.com/docs/connections.html ) on 'Replica Set the Connections section.

 // connection string using mongoose: var uri = 'mongodb://MY_USER: MY_PASSWORD@ ' + 'MY_SERVER-shard-00-00-clv3h.mongodb.net:27017,' + 'MY_SERVER-shard-00-01-clv3h.mongodb.net:27017,' + 'MY_SERVER-shard-00-02-clv3h.mongodb.net:27017/MY_DATABASE' + 'ssl=true&replicaSet=MY_REPLICASET_NAME-shard-0&authSource=MY_ADMIN_DATABASE'; mongoose.connect(uri); var db = mongoose.connection; 

Now it works fine!

+6
source

Add username and password to connect to the database

 mongodb://[username: password@ ]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]] 

Standard connection string format

0
source

Source: https://habr.com/ru/post/1261472/


All Articles