connecting to remote mongodb with nodejs

Viewed 852

i have a remote mongo server and i want to connect to that with nodejs . i tried connecting directly with mongo shell and it was ok ... but i cant connect to that mongodb server in nodejs .. the mongo command for connection :

mongo --host 192.168.10.33 --port 27017 -u mohammad -p "mypassw@12" --authenticationDatabase=access

i only want to convert that command into nodejs connection config.. something like:

uri = mongodb://mohammad:mypassw@12@192.168.10.33:27017/"

3 Answers

The URI should be encoded

uri = "mongodb://mohammad:mypassw%4012@192.168.10.33:27017/access"

mongo.connect(uri, { useNewUrlParser: true }, (err, db) => {});

Connecting to a remote Mongo can sometimes be tricky , mongoose can help a great lot with connecting to your remote db . The code below should be able to do the trick and connect .

const mongoose = require('mongoose');
mongoose.set('useFindAndModify', false);
const uri = "mongodb+srv://user:pass@clusterName.d4zrk.mongodb.net/databaseName?retryWrites=true&w=majority";

mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })

const db = mongoose.connection

db.on('error', (err) => {
    console.log(err)
})
db.once('open', () => {
    console.log('Database Connection Established!')
})

I guess the issue might be with your password, it looks like to contains a special character that is used by the mongodb driver to separate the credentials from the host:

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

If you have a @ in your password, you have to apply an percent encoding it by adding a % character.

Here is the list of character to encode according to mongodb driver documentation: : / ? # [ ] @

Related