Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect with username/password to mongodb using native node.js driver

I'm using native mongo driver in Joyent cloud, the node.js application runs fine locally but in Joyent when I run with the username/password that they provided it fails to connect.

This is the code I use 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);
    // }
    // });
}
});

What's stopping me from connecting successfully?

like image 387
santosh Avatar asked Apr 20 '13 19:04

santosh


People also ask

How use MongoDB native driver?

Connection Guide: connect to a MongoDB instance or replica set. Authentication: configure authentication and log a user in. CRUD Operations: read and write data to MongoDB. Promises and Callbacks: access return values using asynchronous Javascript.

Which drivers are useful to connect node js with MongoDB?

Connect your Node. js applications to MongoDB and work with your data using the Node. js driver. The driver features an asynchronous API that you can use to access method return values through Promises or specify callbacks to access them when communicating with MongoDB.


3 Answers

Easier if you just use MongoClient

MongoClient.connect('mongodb://admin:password@localhost:27017/db', function (err, db) {
like image 130
Jonathan Ong Avatar answered Oct 13 '22 01:10

Jonathan Ong


Standard URI connection scheme is:

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

For Example:

mongodb://admin:[email protected]/

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

like image 25
VAIBHAV GOUR Avatar answered Oct 12 '22 23:10

VAIBHAV GOUR


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();
});
like image 31
Jamil Noyda Avatar answered Oct 13 '22 01:10

Jamil Noyda