How I can get names collection list in mongoose?
Older answers -
mongoose.connection.db.collectionNames is not a function (
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();
});
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With