试图从mongoose获取集合列表

时间:2013-11-13 18:18:45

标签: node.js mongodb mongoose

我试图使用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;
    });

唯一的问题是名称返回为undefined。那么甚至可以使用vanilla mongoose返回集合列表吗?

4 个答案:

答案 0 :(得分:42)

刚刚看到这个答案,虽然它可能在我看来collectionNames从可用的函数名称中移除时有用listCollections

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

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

答案 1 :(得分:4)

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

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

答案 2 :(得分:4)

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

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

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

console.log(names);

此解决方案适用于 mongoose 4.4.19

答案 3 :(得分:0)

如果您只使用Mongoose Models,那就是您所需要的:

const connection = mongoose.connection;
Object.keys(connection.models).forEach((collection) => {
  // You can get the string name.
  console.info(collection);
  // Or you can do something else with the model.
  connection.models[collection].remove({});
});