如何使用本机 node.js 驱动程序使用用户名/密码连接到 mongodb

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16124255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:15:17  来源:igfitidea点击:

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

node.jsnode-mongodb-nativejoyent

提问by santosh

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:

我在 Joyent 云中使用本机 mongo 驱动程序,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);
    // }
    // });
}
});

Has anyone used native node.js driver in Joyent.

有没有人在 Joyent 中使用过原生 node.js 驱动程序。

Thanks

谢谢

回答by Jonathan Ong

Easier if you just use MongoClient

如果您只使用 MongoClient 会更容易

MongoClient.connect('mongodb://admin:password@localhost:27017/db', function (err, db) {

回答by VAIBHAV GOUR

Standard URI connection scheme is:

标准的 URI 连接方案是:

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/

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

回答by Jamil Noyda

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();
});