[英]How to connect to mongodb and How to print list of all collection from a dabase in mongodb using node.js program
Hi I tried to connect to mongodb and print all collection from a dabase in mongodb using node.js program but i am getting error. 嗨,我尝试连接到mongodb并使用node.js程序从mongodb中的dabase打印所有集合,但是我遇到了错误。 Code I tried is as below. 我尝试的代码如下。
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
Kindly help me to fix this error 请帮助我解决此错误
You don't need to select a database. 您无需选择数据库。 You already did that in the connection string: mongodb://ipaddressofmywebsite:27017/databasename
. 您已经在连接字符串中完成了此操作: mongodb://ipaddressofmywebsite:27017/databasename
。 This should work: 这应该工作:
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);
});
}
});
Here is the docs for MongoClient
- About getting the collection names 这是MongoClient
的文档-关于获取集合名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.