试图从mongoose获得collections列表

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

唯一的问题是名称返回未定义。 那么,甚至有可能只用香草mongoose返回一个collections列表?

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

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

刚刚遇到这个答案,虽然它可能已经工作,似乎collectionNames已被删除可用的函数名称赞成listCollections

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

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

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

 var mongoose = require('mongoose'); var collections = mongoose.connections[0].collections; var names = []; Object.keys(collections).forEach(function(k) { names.push(k); }); console.log(names); 

这个解决scheme适用于4.4.6的mongoose

如果您只使用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({}); });