Reputation: 131
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@[email protected]:27017/"
Upvotes: 5
Views: 1930
Reputation: 76
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:[email protected]/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!')
})
Upvotes: 1
Reputation: 10960
The URI should be encoded
uri = "mongodb://mohammad:mypassw%[email protected]:27017/access"
mongo.connect(uri, { useNewUrlParser: true }, (err, db) => {});
Upvotes: 1
Reputation: 747
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: : / ? # [ ] @
Upvotes: 0