How to connect with username/password to mongodb u

2020-06-15 03:04发布

I'm using native mongo driver in Joyent cloud, the node.js application runs fine locally but in Joyent when i run with usrname/pswd that they provided it fails to connect. following is the code used to connect:

var db = new MongoDB(dbName, new Server('localhost', 27017 , {auto_reconnect: true}), {w: 1});
db.open(function(e, db){
if (e) {
    console.log(e);
} else{
    console.log('connected to database :: ' + dbName);
    //db.admin().authenticate('admin', '+(uihghjk', function(de , db){
    // if(e){
    //     console.log("could not authenticate");
    // }else {
    //console.log('connected to database :: ' + dbName);
    // }
    // });
}
});

Has anyone used native node.js driver in Joyent.

Thanks

3条回答
2楼-- · 2020-06-15 03:39

Standard URI connection scheme is:

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

For Example:

mongodb://admin:pass@abc.com/

Reference: https://docs.mongodb.com/manual/reference/connection-string/

查看更多
对你真心纯属浪费
3楼-- · 2020-06-15 03:51

Easier if you just use MongoClient

MongoClient.connect('mongodb://admin:password@localhost:27017/db', function (err, db) {
查看更多
对你真心纯属浪费
4楼-- · 2020-06-15 03:54

the working code would be like this

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster0-saugt.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
    // creating collection
    const collection = client.db("test").collection("devices");
    // perform actions on the collection object
    client.close();
});
查看更多
登录 后发表回答