Skip to content

Instantly share code, notes, and snippets.

@edwardhotchkiss
Created December 27, 2011 02:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edwardhotchkiss/1522555 to your computer and use it in GitHub Desktop.
Save edwardhotchkiss/1522555 to your computer and use it in GitHub Desktop.
/**
* Uses MongooseJS to Connect to MongoDB
* .Maps out all collections within
*/
var mongoose = require('mongoose')
, MONGO_DB = 'mongodb://localhost/test';
mongoose.connect(MONGO_DB);
mongoose.connection.on('open', function(){
mongoose.connection.db.collectionNames(function(error, collections) {
if (error) {
throw new Error(error);
} else {
collections.map(function(collection) {
console.log('found collection %s', collection.name);
});
}
});
});
mongoose.connection.on('error', function(error){
throw new Error(error);
});
/* EOF */
@jurby
Copy link

jurby commented May 10, 2012

Thanks so much for show. But returns this output: 'collection found [object Object] ".
Here is a fix:

      ...
      names.map(function(item) {
        console.log('found collection %s', item.name);
      });
      ...

@edwardhotchkiss
Copy link
Author

edwardhotchkiss commented May 10, 2012 via email

@jurby
Copy link

jurby commented May 10, 2012

Code:

console.log(util.inspect(item));

Output: (2 items in mongodb - mongodb://localhost/test)
{ name: 'test.threads' }
{ name: 'test.system.indexes' }

Versions:

  • mongodb: 2.0.4
  • nodejs: 0.6.14

@jurby
Copy link

jurby commented May 11, 2012

Yes there is.

Mongodb in MONGO term. returns an array of strings:

Db.getCollectionNames ()
["System.indexes", "threads"]

In node script return:

console.log(util.inspect(names)); => [ { name: 'test.threads' }, { name: 'test.system.indexes' } ]

Once more many thanks for your show. Take care.

@shmuliko
Copy link

shmuliko commented Nov 3, 2016

mongoose.connection.on('open', function (ref) { mongoose.connection.db.collections(function(error, collections) { if (error) { throw new Error(error); } else { collections.map(function(collection) { console.log('found collection %s', collection.s.name); }); } });

@pravinvram
Copy link

is the new name now listCollections ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment