RSKMR
RSKMR

Reputation: 1892

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

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?

Upvotes: 0

Views: 902

Answers (1)

rafaismyname
rafaismyname

Reputation: 188

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!

Upvotes: 1

Related Questions