【问题标题】:How do I connect to mongodb with node.js (and authenticate)?如何使用 node.js 连接到 mongodb(并进行身份验证)?
【发布时间】:2011-01-14 07:01:55
【问题描述】:

如何使用 node.js 连接到 mongodb?

我有 node-mongodb-native 驱动程序。

显然有 0 个文档。

是这样的吗?

var mongo = require('mongodb/lib/mongodb'); 
var Db= new mongo.Db( dbname, new mongo.Server( 'mongolab.com', 27017, {}), {}); 

我把用户名和密码放在哪里?

另外我该如何插入一些东西?

谢谢。

【问题讨论】:

标签: javascript node.js mongodb authentication connection


【解决方案1】:

the source:

连接后:

Db.authenticate(user, password, function(err, res) {
  // callback
});

【讨论】:

  • 我不敢相信这个答案因语法错误而受到如此多的支持......回调定义不明确。请参阅下面的解决方案和更合适的源链接:stackoverflow.com/a/15191273/1060487
  • 我第一次尝试这个并没有用,但那是因为我用错了。我在管理员中使用了我的用户的凭据。我专门为数据库创建了一个用户并使用了这些凭据。像魅力一样工作。谢谢!
  • Db 自驱动程序版本 3.1 起不再具有身份验证方法。 mongodb.github.io/node-mongodb-native/3.1/api/Db.html
【解决方案2】:

每个人都应该使用这个源链接:

http://mongodb.github.com/node-mongodb-native/contents.html

问题的答案:

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('integration_tests', new Server("127.0.0.1", 27017,
 {auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});

// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  // Add a user to the database
  db.addUser('user', 'name', function(err, result) {
    assert.equal(null, err);

    // Authenticate
    db.authenticate('user', 'name', function(err, result) {
      assert.equal(true, result);

      db.close();
    });
  });
});

【讨论】:

  • 为什么总是将用户添加到数据库中?
  • 这是一个例子,复制自我发布的驱动手册链接...连接方法是有用的部分。
  • 仅供参考,希望对某人有所帮助..这不起作用,因为null != {}并且此检查失败:assert.equal(null, err);
  • 也许手动示例现在已经过时了,还有更新版本的 Mongo,谢谢你的信息!
【解决方案3】:
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;    
MongoClient.connect('mongodb://'+DATABASEUSERNAME+':'+DATABASEPASSWORD+'@'+DATABASEHOST+':'DATABASEPORT+'/'+DATABASENAME,function(err, db){  
      if(err) 
        console.log(err);
      else
      {
        console.log('Mongo Conn....');

      }
    });
//for local server 
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DATABASEHOST+':'+DATABASEPORT+'/'+DATABASENAME,function(err, db){  
      if(err) 
        console.log(err);
      else
      {
        console.log('Mongo Conn....');

      }
    });

【讨论】:

  • 完美...谢谢...你刚刚离开了连接运算符'@'+DATABASEHOST+':' + DATABASEPORT @Viral Patel
【解决方案4】:

我发现使用 Mongo 网址很方便。我将 URL 存储在环境变量中并使用它来配置服务器,而开发版本使用没有密码的默认 URL。

网址格式为:

export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD@DBHOST:DBPORT/DBNAME

以这种方式连接的代码:

var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;

mongo_connect(DATABASE_URL, mongodb_server_options, 
      function(err, db) { 

          if(db && !err) {
          console.log("connected to mongodb" + " " + lobby_db);
          }
          else if(err) {
          console.log("NOT connected to mongodb " + err + " " + lobby_db);
          }
      });    

【讨论】:

  • 如果用户在 DBNAME 之外的另一个数据库中(如 admin),您必须将选项 ?authSource=admin 添加到 URL。
【解决方案5】:

我的版本:

var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://user:pass@dhost:port/baseName', function(err, db) {
    if (err) {
        console.error(err);
    }
    var collection = db.collection('collectionName');
    collection.find().toArray(function(err, docs) {
        console.log(docs);
    });
});

【讨论】:

    【解决方案6】:

    我推荐我刚刚创建的mongoskin

    var mongo = require('mongoskin');
    var db = mongo.db('admin:pass@localhost/mydb?auto_reconnnect');
    db.collection('mycollection').find().toArray(function(err, items){
       // do something with items
    });
    

    mongoskin 同步吗?不,它是异步的。

    【讨论】:

      【解决方案7】:

      这是从“管理员”进行身份验证的新方法,然后切换到所需的数据库以进行进一步操作:

         var MongoClient = require('mongodb').MongoClient;
      var Db = require('mongodb').Db, Server = require('mongodb').Server ,
          assert = require('assert');
      
      var user = 'user';
      var password = 'password';
      
      MongoClient.connect('mongodb://'+user+':'+password+'@localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
          if(err){
              console.log("Auth Failed");
              return;
          }
          console.log("Connected");
          db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
              docs.each(function(err, doc) {
                if(doc) {
                  console.log(doc['_id']);
                }
              });
          });
      
          db.close();
      
      }); 
      

      【讨论】:

      • 这只是db的连接名称。
      【解决方案8】:

      这对我有用:

      Db.admin().authenticate(user, password, function() {} );
      

      【讨论】:

      • 不适用于较新版本的驱动程序。 db.authenticate() 方法不再存在。至少,它在我使用的 node.js 3.1 驱动程序中不存在。我在 Node Inspector 控制台中收到“db.authenticate is not a function”错误。
      【解决方案9】:

      你可以这样做

      var db = require('mongo-lite').connect('mongodb://localhost/test')
      

      more details ...

      【讨论】:

      • 喜欢这个图书馆。元素一些回调。甚至比 mongo-skin 更合身
      【解决方案10】:

      如果原生驱动还是有问题,也可以看看 sleepy mongoose。这是一个 python REST 服务器,您可以通过节点请求简单地访问它以访问您的 Mongo 实例。 http://www.snailinaturtleneck.com/blog/2010/02/22/sleepy-mongoose-a-mongodb-rest-interface/

      【讨论】:

        【解决方案11】:

        以@mattdlockyer 提供的链接作为参考,这对我有用:

        var mongo = require('mongodb');
        var server = new mongo.Server(host, port, options);
        db = new mongo.Db(mydb, server, {fsync:true});
        db.open(function(err, db) {
            if(!err) {
                console.log("Connected to database");
                db.authenticate(user, password, function(err, res) {
                    if(!err) {
                        console.log("Authenticated");
                    } else {
                        console.log("Error in authentication.");
                        console.log(err);
                    }
                });
            } else {
                console.log("Error in open().");
                console.log(err);
            };
        });
        
        exports.testMongo = function(req, res){
            db.collection( mycollection, function(err, collection) {
                collection.find().toArray(function(err, items) {
                    res.send(items);
                });
            });
        };
        

        【讨论】:

          【解决方案12】:

          克里斯的回答有轻微的错别字。

          Db.authenticate(user, password, function({ // callback }));
          

          应该是

          Db.authenticate(user, password, function(){ // callback } );
          

          另外,根据您的 mongodb 配置,您可能需要先连接到 admin 和 auth,然后再转到其他数据库。如果您没有将用户添加到您尝试访问的数据库中,就会出现这种情况。然后就可以通过admin auth,然后切换db,然后随意读写。

          【讨论】:

            【解决方案13】:
            const { MongoClient } = require('mongodb');
            // or as an es module:
            // import { MongoClient } from 'mongodb'
            
            // Connection URL
            const url = 'mongodb://localhost:27017';
            const client = new MongoClient(url);
            
            // Database Name
            const dbName = 'myProject';
            
            async function main() {
              // Use connect method to connect to the server
              await client.connect();
              console.log('Connected successfully to server');
              const db = client.db(dbName);
              const collection = db.collection('documents');
            
              // the following code examples can be pasted here...
            
              return 'done.';
            }
            
            main()
               //what to do next
              .then(console.log)
               //if there is an error
              .catch(console.error)
              // what to do in the end(function result won't matter here, it will execute always).
              .finally(() => client.close());
            

            您可以在此处的文档中找到更多信息:https://mongodb.github.io/node-mongodb-native/4.1/

            【讨论】:

              【解决方案14】:

              我正在使用 Mongoose 连接到 mongodb。 使用以下命令安装 mongoose npm

              npm 安装猫鼬

              var mongoose = require('mongoose');
              mongoose.connect('mongodb://localhost:27017/database_name', function(err){
                  if(err){
                      console.log('database not connected');
                  }
              });
              var Schema = mongoose.Schema;
              var userschema = new Schema ({});
              var user = mongoose.model('collection_name', userschema);
              

              我们可以使用这样的查询

              user.find({},function(err,data){
                       if(err){
                       console.log(err);
                       }
                      console.log(data);
                  });
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2017-03-24
                • 1970-01-01
                • 2018-01-25
                • 2016-10-21
                • 2023-04-05
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多