Jackson
Jackson

Reputation: 914

How get collections list in mongoose?

How I can get names collection list in mongoose?
Older answers -
mongoose.connection.db.collectionNames is not a function (

Upvotes: 5

Views: 18750

Answers (3)

Code Uniquely
Code Uniquely

Reputation: 6373

if you just want an array containing the collection names then you can use

const collections = Object.keys(mongoose.connection.collections);

and you get a result like this

[
  "identitycounters",
  "roles",
  "user"
]

depending on what's in your db.

Upvotes: 3

derFBeste
derFBeste

Reputation: 381

To get collections now it's:connection.db.collections.

Upvotes: 1

Indeed, mongoose.connection.db.collectionNames was dropped in favor of mongoose.connection.db.listCollections.

const mongoose = require('mongoose');

const connection = mongoose.connect('mongodb://localhost:27017');

connection.on('open', function () {
    connection.db.listCollections().toArray(function (err, names) {
      if (err) {
        console.log(err);
      } else {
        console.log(names);
      }

      mongoose.connection.close();
    });
});

Upvotes: 16

Related Questions