繁体   English   中英

如何连接到mongodb以及如何使用node.js程序从mongodb中的dabase打印所有集合的列表

[英]How to connect to mongodb and How to print list of all collection from a dabase in mongodb using node.js program

嗨,我尝试连接到mongodb并使用node.js程序从mongodb中的dabase打印所有集合,但是我遇到了错误。 我尝试的代码如下。

     var MongoClient = require('mongodb').MongoClient;


    MongoClient.connect("mongodb://ipaddressofmywebsite:27017/databasename", function(err, db) {
      if(!err) {
        console.log("We are connected");
         var  m = new MongoClient();
        var db = m.selectDB("databasename");
        var list= db.getCollectionNames();
        console.log(list);
      }
    });



        **I get the following error**


            throw err
                  ^
        TypeError: m.selectDB is not a function


When I tried the below code as suggested in this page also i get error.

    var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://websiteipaddress/databasename", 
    function(err, db) { // The db is passed in here.
      if(!err) {
        console.log("We are connected");
        var list= db.getCollectionNames();
        console.log(list);
      }
    });



 **Error i get is**

        throw err
              ^

    TypeError: db.getCollectionNames is not a function

请帮助我解决此错误

您无需选择数据库。 您已经在连接字符串中完成了此操作: mongodb://ipaddressofmywebsite:27017/databasename 这应该工作:

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect("mongodb://ipaddressofmywebsite:27017/databasename", 
    function(err, db) { // The db is passed in here.
      if(!err) {
        console.log("We are connected");
        db.collectionNames(function(err, names) {
            console.log(names);
        });
      }
    });

MongoClient的文档-关于获取集合名称

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM