Reputation: 914
How I can get names collection list in mongoose?
Older answers -
mongoose.connection.db.collectionNames is not a function (
Upvotes: 5
Views: 18750
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
Reputation: 748
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