我使用的是本地蒙戈司机Joyent的云,Node.js的应用程序运行正常,但局部在Joyent公司当我与usrname运行/ PSWD他们提供连接失败。 以下是用于连接的代码:
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);
// }
// });
}
});
有没有人在Joyent公司使用原生的node.js驱动程序。
谢谢
容易,如果你只是用MongoClient
MongoClient.connect('mongodb://admin:password@localhost:27017/db', function (err, db) {
标准URI连接方案是:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
例如:
mongodb://admin:pass@abc.com/
参考: https://docs.mongodb.com/manual/reference/connection-string/
工作代码会是这样
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();
});
文章来源: How to connect with username/password to mongodb using native node.js driver