【问题标题】:Nodejs + Mongo db connect with server database with username and passwordNodejs + Mongo db 使用用户名和密码连接服务器数据库
【发布时间】:2019-06-23 20:03:34
【问题描述】:

我正在处理一个现有项目。这里使用多个数据库。我正在努力使用用户名和密码连接服务器数据库。

目前我正在使用没有用户名和密码的本地数据库。它工作正常。

我正在使用 mongodb npm 模块。

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

});

谁能帮忙用用户名和密码连接服务器数据库。

注释。我期待使用相同的 mongodb npm 模块。不想使用 mongoose,因为它已经在这个项目中实现了许多 api;s..

预期结果:使用用户名和密码连接服务器数据库.. 或者有什么替代方法?

【问题讨论】:

    标签: node.js database mongodb mongoose mongodb-query


    【解决方案1】:

    只需使用 Mongo 的连接 URL,如 mogo's 文档中所述:

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

    所以你的代码看起来像这样(根据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();
    });
    

    祝你好运!

    【讨论】:

    猜你喜欢
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2023-01-11
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多