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?
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.
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.
Easier if you just use MongoClient
MongoClient.connect('mongodb://admin:password@localhost:27017/db', function (err, db) {
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/
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With