Nodejs + Mongo db connect with server database with username and password

旧时模样 提交于 2020-01-24 01:35:06

问题


I am working on an existing project. Here using multiple database. I am struggling to connect the server database with username and password.

Currently now I am using local database without username and password. It's working fine.

I am using mongodb npm module.

db.js

var mongodb = require('mongodb');
module.exports.init = function (callback) {
  var server = new mongodbs.Server('localhost', 27017, {})
  //var server =  new mongodbs.Server('abc.com', 27017, username , password,  {})

  module.exports.db = {};
  new mongodb.Db('user', server, {
    w: 1
  }).open(function (error, client) {
    module.exports.user = client;
    module.exports.user_tokens = client.collection('tokens');
    module.exports.user_session = client.collection('session');
    module.exports.user_consent = client.collection('consent');
    module.exports.user_client = client.collection('client');

    callback(error);
  });

  new mongodb.Db('employee', server, {
    w: 1
  }).open(function (error, client) {
    module.exports.employee = client;
    module.exports.employee_list = client.collection('list');
    module.exports.employee_detail = client.collection('detail');
    callback(error);
  });

};

index.js

var mongoUtil = require('./db');
mongoUtil.init(function (error) {
if (error)
  throw error;
});    
router.post('/test', function (req, res) {
  var collection = mongoUtil.employee_list;
  collection.insert({
    name: 'test'
  }, function (err, item) {
    if (!err && item) {
      console.log("success")
    } else {
      console.log("failure")
    }
  });

});

Can any one please help to connect the server db with username and password.

Notes. I am expecting to use same mongodb npm module. Don;t want to use mongoose because its already implemented many api;s in this project..

Expect result : connect server db with username and password.. Or have any alternate methods?


回答1:


Just use Mongo's Connection URL, as described in mogo's docs:

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

So your code would look like this (accordingly with mongodb's npm module manual):

const MongoClient = require('mongodb');

// Connection URL
const url = 'mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]]';

// Database Name
const dbName = '[dbName]';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

Best luck!



来源:https://stackoverflow.com/questions/54442315/nodejs-mongo-db-connect-with-server-database-with-username-and-password

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!