试图从mongoose获取集合列表

Aus*_*vis 13 mongoose mongodb node.js

我正在尝试使用mongoose返回dbs集合的列表.我按照此处列出的指示,但http://grokbase.com/t/gg/mongoose-orm/122xxxr7qy/mongoose-get-a-list-of-all-collections.所以这是我的代码

var mongoose = require('mongoose');
    //if (mongoose.connection.readyState == 0){//checks if already connected to the database
    console.log("creating connection to the database");
    var Config = require('../configs/config');
    var config = new Config();
    config = config.getConfig().db.dev;

    if (mongoose.connection.readyState = 0 ) {
    mongoose.connect("mongodb://austin:password1@paulo.mongohq.com:10023/test1");
    console.log('mongoose readyState is ' + mongoose.connection.readyState);
    }
    var collection;

    mongoose.connection.on('open', function (ref) {
        console.log('Connected to mongo server.');
    });

    //trying to get collection names
    mongoose.connection.db.collectionNames(function (err, names) {
        console.log(names); // [{ name: 'dbname.myCollection' }]
        module.exports.Collection = names;
    });
Run Code Online (Sandbox Code Playgroud)

唯一的问题是名称返回未定义.那么甚至可以使用香草猫鼬返回集合列表吗?

Squ*_*ivo 44

刚刚看到这个答案,虽然它可能已经工作,但它似乎collectionNames已从可用的功能名称中删除而有利于listCollections

这个其他堆栈溢出帖子有一个工作示例:https://stackoverflow.com/a/29461274/4127352

以下是原始文档的链接:http: //mongodb.github.io/node-mongodb-native/2.0/meta/changes-from-1.0/

  • 危险的例子,我快速复制代码并没有注意到它丢弃了数据库中的集合.所以请编辑以包含列出集合的实际代码所以小心! (2认同)

小智 8

连接后尝试运行您的集合名称功能。

mongoose.connection.on('open', function (ref) {
    console.log('Connected to mongo server.');
    //trying to get collection names
    mongoose.connection.db.listCollections().toArray(function (err, names) {
        console.log(names); // [{ name: 'dbname.myCollection' }]
        module.exports.Collection = names;
    });
})
Run Code Online (Sandbox Code Playgroud)

  • -1,因为它不再起作用了,请更新答案,然后我将删除downvote。对于其他人,请参见Squivo的答案。 (19认同)
  • -1,因为,这是无效的答案。使用`mongoose.connection.db.listCollections()。toArray((error,collections => {// ...}}) (9认同)
  • (自@zbr和@Vikram发表评论以来,此答案已得到纠正) (2认同)

Rog*_*ger 5

这是我如何设法获取连接的数据库上的所有名称。

var mongoose = require('mongoose');
var collections = mongoose.connections[0].collections;
var names = [];

Object.keys(collections).forEach(function(k) {
    names.push(k);
});

console.log(names);
Run Code Online (Sandbox Code Playgroud)

此解决方案适用于mongoose 4.4.19

  • 这不会列出连接数据库中的集合!它列出了使用 `mongoose.model` 函数注册的集合。它甚至在空数据库上列出集合,实际上甚至在连接到一个数据库之前。 (8认同)