21

我正在尝试使用 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;
    });

唯一的问题是名称返回未定义。那么是否甚至可以仅使用 vanilla mongoose 返回集合列表?

4

5 回答 5

46

刚刚遇到这个答案,虽然它可能在它出现的时候已经工作了,它似乎collectionNames已经从可用的函数名称中删除了listCollections

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

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

于 2015-06-05T21:18:01.533 回答
27

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

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;
    });
})
于 2013-11-13T22:36:14.060 回答
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);

该解决方案在mongoose 4.4.19上运行良好。

于 2016-06-24T01:08:49.703 回答
0

如果您只使用 Mongoose 模型,这就是您所需要的:

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({});
});
于 2016-12-19T09:33:55.740 回答
0

与上面的最佳答案类似,但此代码显示每个集合的名称,没有其他附加信息(如类型、选项、信息等)。

const namesList = [];
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) {
    for (let i = 0; i < names.length; i++) {
      // gets only the name and adds it to a list
      const nameOnly = names[i].name;
      namesList.push(nameOnly);
    }
    console.log(namesList);
    module.exports.Collection = namesList;
  });
});
于 2021-08-23T12:18:32.040 回答