Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (

like image 657
Jackson Avatar asked Dec 03 '22 13:12

Jackson


2 Answers

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();
    });
});
like image 200
Luis Diego Hernández Avatar answered Dec 23 '22 15:12

Luis Diego Hernández


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.

like image 45
Code Uniquely Avatar answered Dec 23 '22 14:12

Code Uniquely